I have tried to deploy my React/Node.js project to Vercel. As client and server are placed on different URL, I have got a CORS problem. I had used cors
library and different settings. In the end when I get some data from server (list of news) it works OK 7 in 10 times, other 3 times it shows me CORS error with same API. But when I try to log in or sign up it always shows CORS error.
On Vercel I filled out all variables which I use for server.
My index.js
looks like:
const express = require("express");
const cookieParser = require("cookie-parser");
const cors = require("cors");
const http = require("http");
const dotenv = require("dotenv/config");
const mongoose = require("mongoose");
const routes = require("./src/routes/index.js");
const app = express();
app.use(cors());
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
const PORT = process.env.PORT || 6000;
app.get("/", (req, res) => {
res.send("Express on Vercel");
});
app.use("/api/v1", routes);
const server = http.createServer(app);
mongoose
.connect(process.env.MONGODB_URL, {
useNewUrlParser: true,
useUnifiedTopology: true,
})
.then(() => {
console.log("Mongodb connected");
server.listen(PORT, () => {
console.log(`Server is listening on port ${PORT}`);
});
})
.catch((err) => {
console.log({ err });
process.exit(1);
});
module.exports = app;
Does anyone have any idea why it doesn’t work properly?