When I'm starting my server from localhost, it's not giving me any kind of error. But after deploying to Heroku, it's giving me the following cors error on some specific routes:
No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://127.0.0.1:8080' is therefore not allowed access. The response had HTTP status code 503. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
I have tried almost everything to resolve this error and I have also tried all the possible solutions I found on stack overflow but nothing is working.
My code is simple: there is a login function which is sending a request to an API endpoint and that endpoint is ensuring whether the admin is authenticated or not.
My server code: ( using express js )
const expressApp = require('express');
const port = process.env.PORT || 3000;
const cors = require('cors');
const express = expressApp();
const bodyParser = require('body-parser');
const session = require('express-session');
const adminRoutes = require('./admin/admin-routes');
const userRoutes = require('./users/user-routes');
const bookingRoutes = require('./booking/booking-routes');
const contactRoutes = require('./contact-us/contact-routes');
require('./dbConnection.js');
express.use(function (req, res, next) {
console.log(req.headers);
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
res.header("Access-Control-Allow-Methods", "POST,DELETE,PUT,GET,OPTIONS");
res.header("Access-Control-Allow-Headers", req.headers['access-control-request-headers']);
res.header("Access-Control-Request-Method", req.headers['access-control-request-method']);
next();
});
The client side is :
fetch(url, {
method: "POST",
password: this.password,
body: JSON.stringify({
bodyData: { email }
}),
headers: {
'Access-Control-Allow-Origin': '*',
"Content-Type": "application/json"
}
}).then(res => {
return res.json()
}).then(user => {
// somthing here
}).catch(error => {
console.log(error);
})