8

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.

user2401221
  • 519
  • 2
  • 9
  • 19
  • Adding the `Access-Control-Allow-Origin` is correct, but it seems like your code isn't adding it. Check the headers using Firebug or Chrome dev tools on network tab. – SilverlightFox Mar 07 '14 at 09:13
  • It be good to see the frontend code that was making the request also. I have been battling with similar issues for the past few hours. I had issues with malformed POST data being sent (using jquery). I have the two headers you have there, and also `res.header('Access-Control-Allow-Methods', 'POST');` you can specify multiple rest methods by comma seperated `'POST, GET'` etc. That might help – Lex Jun 13 '14 at 05:21

2 Answers2

1

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();
});
KARTHIKEYAN.A
  • 18,210
  • 6
  • 124
  • 133
0

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).

ZachRabbit
  • 5,144
  • 1
  • 23
  • 16
  • I have tried but still the same issue. I have a console.log in allowCrossDomain function and in my app.get(...) and only log in allowCrossDomain function is displayed in the console when I try to access to a page. Actually, a friend with its localhost tries to reach my server and we are on the same network. EDIT : I have added the headers in each app.get()method and it works but it doesn't seem the proper way – user2401221 Mar 07 '14 at 09:27