The code for my backend server clearly allows access to the frontend in the index.js:
require("dotenv").config();
const express = require('express');
const chalk = require('chalk');
const bodyParser = require('body-parser');
const http = require("http")
const app = express();
const port = process.env.PORT || 8000;
const cors = require('cors');
const corsOptions = {
origin: process.env.CLIENT || 'http://localhost:3000',
methods: 'GET,PUT,POST,DELETE',
allowedHeaders: 'Origin, X-Requested-With, Content-Type, Accept',
credentials: true
};
app.use(cors(corsOptions));
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({ extended: true }))
app.get('/', (req, res) => {
res.send('Hello World!');
});
const server = http.createServer(app);
server.listen(port, () => {
console.log(`Server listening on port ${port}`);
});
require('./router')(app);
My frontend, which is a react app also hosted on frontend is not able to send requests to this backend:
Access to XMLHttpRequest at '{backend route}' from origin '{frontend domain}' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
I have double checked the value of process.env.CLIENT
which is the same as the frontend website URL. (https://{myappname}.vercel.app)
Here is my vercel.json
:
{
"version": 2,
"rewrites": [
{
"source": "/(.*)",
"destination": "/"
}
]
}
UPDATE: I just noticed that certain endpoints work on the backend while some don’t. This is abnormal