1

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);
    })
Gino Mempin
  • 12,644
  • 19
  • 50
  • 69
Soha M.
  • 29
  • 3
  • 1
    You must add OPTIONS handling for those routes. And remove the `'Access-Control-Allow-Origin': '*'` from the `headers {…}` object in your frontend code. Access-Control-Allow-Origin is a response header for servers to send, not a request header – sideshowbarker Oct 24 '18 at 00:55
  • Since you are using 'cors' module, just use express.use(cors()); before routing files. Otherwise, put your express.use('cors enable mechanism') before initiate routing. – Shams Nahid Oct 24 '18 at 04:12
  • Thank you so much. My problem is solved now :) – Soha M. Oct 24 '18 at 11:07

0 Answers0