Cors issue while deployment

I have deployed a express server which works with a react app and its a stock market project. i have one repo with two folders as frontend and server and both are deployed separately. The project works perfectly fine with local environment and frontend also works if express server is working locally. I am facing cors issue with error as

login:1 Access to XMLHttpRequest at 'https://sbroker-backend.vercel.app/user/login' from origin 'https://sbroker.vercel.app' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

When i try to make similar request on postman i get “FUNCTION_INVOCATION_FAILED” error. It would be really helpful if anyone could help resolve this error.

const express = require("express");
const app = express();
const userroutes = require("../routes/routelogin");
const profileroutes = require("../routes/routeprofile");
const stockroutes = require("../routes/routestock");
const watchlistroute = require("../routes/routewatchlist");
const database = require("../config/database");
const cookieparser = require("cookie-parser");
const cors = require("cors");
const dotenv = require("dotenv");
const morgan = require("morgan"); // Logging middleware
const login =require("../controllers/login");
// app.use(cors({
  
  // origin: 'http://localhost:3000',
  // methods: 'GET,HEAD,PUT,PATCH,POST,DELETE',
  // credentials: true,
  // optionsSuccessStatus: 204,
// }));
app.use(
	cors({
		origin:["http://localhost:3000","https://sbroker.vercel.app"],
		credentials:true,
	})
)
dotenv.config();
const PORT = process.env.PORT || 4000;

// Connect to the database
database.connect();


app.use(express.json());
app.use(cookieparser());


// Routes
app.use("/user", userroutes);
/*app.post("/user/login",(req,res)=>{
  return res.json({
    success:true,
    message:"login wala chl rha"
  });
});
*/
//app.post("/user/login",login.login);
app.use("/profile", profileroutes);
app.use("/stock", stockroutes);
app.use("/watchlist", watchlistroute);

// Root route
app.get("/", (req, res) => {
  return res.json({
    success: true,
    message: "Your server is up and running....",
  });
});

// Handle 404 errors


// Error handling middleware
// app.use((err, req, res, next) => {
//   console.error("Server error:", err.stack || err.message);
//   res.status(500).json({
//     success: false,
//     message: "An unexpected error occurred",
//     error: process.env.NODE_ENV === "development" ? err.message : undefined,
//   });
// });

// Start the server
app.listen(PORT, () => {
  console.log(`App is running on http://localhost:${PORT}`);
});

Above is index.js.

{ "version": 2, "rewrites": [{ "source": "/(.*)", "destination": "/api" }] }

Above is vercel.json which i took from vercel’s post about express js deployment.
Repo Link
this is the repo link.
frontend link
this is the frontend link
backend link
this is the backend link.
(In frontend code, only login code has backend url in request because without it other things cant be accessed anyways. other components have url of local host)

There’s another community post with 404 debugging tips that might be helpful. Please give these solutions a try and let us know how it goes.

A human should be around soon to offer more advice. But you can also get helpful information quickly by asking v0.

If you’re having trouble deploying an Express app, this guide can help.

You can also ask v0 for suggestions tailored to your own project setup.

Hi @sanchay151, welcome to the Vercel Community!

I think you are on the right path. Can you keep the cors middleware at the top of before you use any other middleware?

hello sir, i made the changes in both post and the code in repo but the error is still the same, can you suggest some other solution

Hi @sanchay151, I see. We’ve this repository that has an Express App serving CORS requests. Can you compare your code to this one and see if you can spot differences?

Frontend is here: https://rrv7.vercel.app/

hii sir, i have observed that if i have a direct function in index.js like
app.post("/user/login",(req,res)=>{ return res.json({ success:true, message:"login wala chl rha" }); });
then it works properly but when i have routes and controllers then, it doesnt work. the repo you sent me also have direct functions but not routes and all. it would be really helpful if you provide some other help

Hi @sanchay151, I think you’re missing router.use(cors(corsConfig)) in the Sbroker/server/routes/routelogin.js at master · sanchay151/Sbroker · GitHub file. Because you are using different routers than the main app.

hi sir i added
`const corsConfig = {
origin: [“http://localhost:3000”, “https://sbroker.vercel.app”],
credentials: true,
};

// Apply CORS middleware to the router
router.use(cors(corsConfig));`
in the code but the issue is still the same. can you suggest some other method to fix this.

This is probably because of an error in your function execution. If you look a the logs in your backend project, my guess is that you will see an error that you’d need to resolve.

Common errors could be input validation, db pooling/connections, or general config changes (environment variables).

hii sir , i have checked logs of backend project but havent found anything.


i have taken help from many of my friends who have deployed multiple sites and they couldnt find the error properly. i would be very thankful if you could help in finding error and deploy it

Can you change the log time to a longer than past 30 minutes? I’d be looking for Error counts on the left :smiley:

1 Like

hii sir, i checked logs and got to know my mongodb cluster wasnt recognising vercel ip address so i fixed it and site is working now. Thanks for your help, really grateful to you

2 Likes

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.