Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Express JS: No 'Access-Control-Allow-Origin' header is present on the requested resource

I have an API running on a server and a front-end client connecting to it to retrieve data. I did some research on the cross domain problem and has it working. However I've not sure what has changed. I am now getting this error in the console:

XMLHttpRequest cannot load https://api.mydomain/api/status. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://beta.mydomain.com' is therefore not allowed access. The response had HTTP status code 502.

I have the following route file:

var express = require('express');
var router = express.Router();
var Assessment = require('../app/models/assessment');

router.all('*', function (req, res, next) {
    res.header('Access-Control-Allow-Origin', '*');
    res.header('Access-Control-Allow-Methods', 'PUT, GET, POST, DELETE, OPTIONS');
    res.header('Access-Control-Allow-Headers', 'Content-Type');
    next();
});


router.post('/api/status', function (req, res, next) {
    getStatus.getStatus(req, res, Assessment);
});

module.exports = router;

And the following JavaScript making an Ajax call to that route:

var user = {
    'uid' : '12345'
};
$.ajax({
    data: user,
    method: 'POST',
    url: 'https://api.mydomain/api/status',
    crossDomain: true,
    done: function () {
    },
    success: function (data) {
        console.log(JSON.stringify(data));
    },
    error: function (xhr, status) {

    }
});

I have tried: Putting the requesting domain in the 'Access-Control-Allow-Origin' header Using the cors module for express Putting my router.all function inside middleware

The requesting domain is HTTP and the api domain is on HTTPS. However, I have had it working while the HTTP was enabled.

Does anyone have any insight into why the 'Access-Control-Allow-Origin' header is not being send?

Thank you

like image 250
Tom Avatar asked Oct 13 '16 15:10

Tom


People also ask

How do I enable Access-Control allow origin in Express?

Enabling CORS The easiest way to get CORS working in Express is by using the cors npm module. That's it. CORS is now enabled. The Access-Control-Allow-Origin header determines which origins are allowed to access server resources over CORS (the * wildcard allows access from any origin).

How do you solve CORS policy no Access-Control allow origin node js?

You can use cors package to help resolve your problem. You can add more core below inside your Node server: const cors = require('cors'); const corsOptions ={ origin:'http://localhost:4000', credentials:true, optionSuccessStatus:200 } app.

How do I enable origin in node?

Run the server with npm nodemon . Navigate to http://localhost:6069/ingredients on your browser. You will be served with these ingredients text items. In this example, cross-origin is allowed because you're currently on the same domain, and you are executing this request from the same domain.


2 Answers

Instead of setting the request headers to your express route, Can you try setting it to express instance itself like this,

var express = require('express');
var app = express();
var Assessment = require('../app/models/assessment');

app.use(function(req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
  next();
});

app.post('/api/status', function (req, res, next) {
    // your code goes here
});

module.exports = app;

Hope this helps!

like image 111
David R Avatar answered Oct 09 '22 05:10

David R


You can also use cors npm for the same.

**npm i cors**

const cors = require('cors')

var corsOptions = {
  origin: '*',
  optionsSuccessStatus: 200 // some legacy browsers (IE11, various SmartTVs) choke on 204 
}
app.use(cors(corsOptions));

var routes = require('./api/routes/route'); //importing route
routes(app); //register the route
like image 32
M J Avatar answered Oct 09 '22 04:10

M J