Dev
Dev

Reputation: 257

XMLHttpRequest at from origin has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource

I am facing an issue with REST APIs. My front-end is in React and APIs are in Express. I intermittently get below error. I've gone through many other similar posts and tried to add HTTP headers to the response without any luck. These calls works fine from Postman client.

"from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource."

So, far I've added below lines to populate HTTP response. The MOST annoying part is these errors only happens with certain web services and not others. They all are identically coded so, it makes it difficult to determine why in certain cases it fails.

My server.js (Express REST app) is as per below ...

 const express = require('express');


const bodyParser = require('body-parser');
const cors = require('cors');
const app = express();
const controllers = require('./controllers');

const logger = require('./logger/logger');
const port = 9000;

app.use(bodyParser.urlencoded({ extended: true }))
app.use(bodyParser.json());
app.use(bodyParser.raw());
controllers.init(app);
app.use(cors());


//Listen server on define port
var server = app.listen(port, () => {
  
    logger.info("API Server is running on port " + port);
})

So, far what I've noticed is, when I add the below segment to include HTTP response headers in my controllers (controllers uses services and models to serve requests), the error disappears EVEN if I remove them after first successful call from my React front-end and this is really bizarre. I use Chrome to test my React front-end. Does this mean Chrome browser is caching something esp. when it comes to the origin? I am worried how this will span out in production? has anyone experienced this sort of behaviour?

app.use((req, res, next) => {
        res.append('Access-Control-Allow-Origin', "*");
        res.append('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
        res.append('Access-Control-Allow-Headers', 'Content-Type');
        next();
    });

Below are the packages I use for the Express API server ..My React front-end uses "react": "^16.13.1"

"dependencies": {
    "body-parser": "^1.19.0",
    "cors": "^2.8.5",
    "express": "^4.17.1",

Upvotes: 1

Views: 6297

Answers (1)

Dev
Dev

Reputation: 257

ok, just managed to get this work by adding the below segment

controllers.init = function (app) {
            app.use((req, res, next) => {
                res.append('Access-Control-Allow-Origin', '*');
                res.append('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
                res.append('Access-Control-Allow-Headers', 'Content-Type');
                next();
            });

in my index.js under controllers folder. index.js contains init for all other controllers....see below

(function (controllers) {
    var appMenuController = require("./appMenuController");
    var applicantTypeController = require("./applicantTypeController");
    var permitApplicationController = require("./permitApplicationController");
    var campusController = require("./campusController");
    var paymentMethodController = require("./paymentMethodController");
    var permitTypeController = require("./permitTypeController");
    var permitController = require("./permitController");
    var permitChangeRequestController = require("./permitChangeRequestController");
    var requestTypeController = require("./requestTypeController");
    var vehicleController = require("./vehicleController");
    
    controllers.init = function (app) {
        app.use((req, res, next) => {
            res.append('Access-Control-Allow-Origin', '*');
            res.append('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
            res.append('Access-Control-Allow-Headers', 'Content-Type');
            next();
        });
        appMenuController.init(app);
        applicantTypeController.init(app);
        permitApplicationController.init(app);
        campusController.init(app);
        paymentMethodController.init(app);
        permitTypeController.init(app);
        permitController.init(app);
        permitChangeRequestController.init(app);
        requestTypeController.init(app);
        vehicleController.init(app)
    }
})(module.exports);

I still don't get it i.e. why Chrome (even Firefox) won't allow HTTP REQ\RESP comms between 2 localhosts on the same host i.e. localhost. Where is a threat in responses originating from the localhost? unless I misunderstood CORS

Upvotes: 2

Related Questions