问题
I have a problem when trying to communicate with my node.js server from ajax requests.
I have configured my server like this :
var allowCrossDomain = 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.use(allowCrossDomain);
When doing my requests I have this error :
XMLHttpRequest cannot load http://10.192.122.180:8181/meters. No 'Access-Control-Allow- Origin' header is present on the requested resource. Origin 'http://localhost:6161' is therefore not allowed access.
When I type URL in a browser it works. I have read many things about CORS, same origin policy but now I'm quite lost.
Could someone help me please ?
Thanks.
回答1:
My guess is that you're serving the page before your middleware (allowCrossDomain
) gets a chance to run.
If you're using Express 3, try the following:
app.use(allowCrossDomain);
app.use(app.router);
If you're using Express 4, make sure your app.use(allowCrossDomain)
call is before the rest of your routes (app.get
and such).
回答2:
To solve this problem use the following code in server.js
app.use(function(req, res, next) {
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Methods', 'GET, POST');
res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type, Authorization');
next();
});
来源:https://stackoverflow.com/questions/22230520/no-access-control-allow-origin-header-is-present-on-the-requested-resource-node