Search code examples
node.jsexpressxmlhttprequestcors

No 'Access-Control-Allow-Origin' header is present on the requested resource in Express app


I have an Express app running on same server with my Web app. I'm trying to make a XMLHttpRequest to my Express app and I get this error:

Access to XMLHttpRequest at 'http://10.0.0.222:9999/' from origin 'http://10.0.0.222:8080' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

Though in my app this header is clearly 'present'. App code:

var cors = require('cors')
const util = require('util');
var inspect = require('eyes').inspector({maxLength: false})
const express = require('express');
var bodyParser = require('body-parser')
const app = express();

app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());

var corsOptions = {
  origin: 'http://10.0.0.222:8080',
  optionsSuccessStatus: 200, // some legacy browsers (IE11, various SmartTVs) choke on 204
}

app.post('/', cors(corsOptions), function (req, res) {
        console.dir(req.body, {depth: null});
        res.send('a');
});

const PORT = process.env.PORT || 9999;
app.listen(PORT, () => {
  console.log(`Server listening on port ${PORT}...`);
});

XMLHttpRequest Code:

var xhr = new XMLHttpRequest();
xhr.open("POST", 'http://10.0.0.222:9999', true);
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.send(goodJSON)

Why do I still get this error even though the origin option has my web app's host included?


Solution

  • It won't work because you have placed the headers in the base route i.e /.

    You must check the headers before resolving the route. In your case route is already resolved and then you are applying the cors headers.

    Use this:

    app.use('/', cors(corsOptions));      or     app.use(cors(corsOptions));
    
    app.post('/', function (req, res) {
        console.dir(req.body, {depth: null});
        res.send('a');
    });
    

    Applying cors in app.use will add the headers. After that path will be resolved and it won't throw the error