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

Issue

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.

Answered By – Dhananjay Sharma

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published