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.

2
  • 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. Commented Mar 7, 2014 at 9: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 Commented Jun 13, 2014 at 5:21

2 Answers 2

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(); }); 
Sign up to request clarification or add additional context in comments.

Comments

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

1 Comment

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.