Hi everyone,
I am getting this CORS error message when I try to fetch data in my application. The ‘Access-Control-Allow-Origin' value is in the response header locally, but not on the live app that is deployed with Vercel.
Error Message: Access to XMLHttpRequest at ‘<server>’ from origin ‘<client>’ has been blocked by CORS policy: No ‘Access-Control-Allow-Origin’ header is present on the requested resource.
I have tried two tried-and-true approaches and both don’t work when deployed: app.use(cors()) and res.header('Access-Control-Allow-Origin', 'http://localhost:8000').
I have looked through posts with similar issues and couldn’t solve my problem.
I have included my index.js, vercel.json, and package.json files.
Any help is greatly appreciated! Thank you!
Code and Configuration:
Index.js (Express)
const express = require('express');
const cors = require('cors');
const bodyParser = require('body-parser');
const router = require('./routes/router');
const dotenv = require('dotenv');
const env = process.env.NODE_ENV || '';
dotenv.config();
const app = express();
// Approach 1: app.use(cors()) - doesn't work when deployed
const corsOptions = {
methods: 'GET',
allowedHeaders: 'Content-Type, Authorization',
origin: 'http://localhost:8000',
credentials: true,
optionSuccessStatus: 200,
};
app.use(cors(corsOptions));
app.use(bodyParser.json());
app.use(
bodyParser.urlencoded({
extended: false,
})
);
// Approach 2: res.header(key, value) - doesn't work when deployed
/*
app.use((req, res, next) => {
const origin = req.headers.origin;
console.log('origin', origin);
res.header(
'Access-Control-Allow-Origin',
'http://localhost:8000'
);
res.header('Access-Control-Allow-Methods', 'GET');
res.header('Access-Control-Allow-Headers', 'Content-Type, Authorization');
if (req.method === 'OPTIONS') {
return res.status(200).end();
}
next();
});
*/
app.use('/', router);
app.use('/tiers', router);
app.use('/members', router);
const port = 4000;
const server = app.listen(port, () => {
console.log(`Server is running on port ${port} in ${env} mode`);
});
Vercel.json
{“version”: 2,“builds”: [{“src”: “./index.js”,“use”: “@vercel/node”}],“routes”: [{“src”: “/(.*)”,“dest”: “/”}]}
PACKAGE.JSON
{
"name": "server",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"start": "NODE_ENV=production node ./index.js",
"dev": " NODE_ENV=development nodemon ./index.js localhost 4000 --env-file=.env.development",
"prod": "NODE_ENV=production nodemon ./index.js localhost 4000 --env-file=.env.production",
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"axios": "^1.6.8",
"body-parser": "^1.20.2",
"cors": "^2.8.5",
"dotenv": "^16.4.5",
"express": "^4.18.3",
"nodemon": "^3.1.0",
"patreon": "^0.4.1"
},
"engines": {
"node": "24.x"
}
}