Search code examples
javascriptnode.jsreactjsexpresscors

Enabling CORS with Express.js to allow multiple ports to communicate


I'm trying to do API calls with React and Axios from my front end (localhost:3000) to my back end (localhost:4567), but I keep getting this error:

Access to XMLHttpRequest at 'localhost:4567' from origin 'http://localhost:3000' has been blocked by CORS policy: Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https.

I have tried to allow CORS by adding this to my back end code, which uses express.js:

const cors = require("cors");
app.use(function(req, res, next) {
    res.header("Access-Control-Allow-Origin", "localhost:3000");
    res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, 
         Accept");
    next();
});

But it does not seem to have made a difference. Any ideas on how to allow my API calls from one port to another?


Solution

  • Enable CORS in express:

    app.use(function (req, res, next) {
        let origin = req.headers.origin;
        res.header("Access-Control-Allow-Origin", req.headers.host.indexOf("localhost") > -1 ? "http://localhost:3000" : origin);
        res.header("Access-Control-Allow-Methods", "GET,HEAD,OPTIONS,POST,PUT");
        res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Authorization");
        res.header('Access-Control-Allow-Credentials', true);
        next();
    });
    

    Use above lines below the var app = express();

    Note: There is no need for external package dependency on cors.