Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
78
rated 0 times [  81] [ 3]  / answers: 1 / hits: 16095  / 12 Years ago, mon, april 9, 2012, 12:00:00

I'm developing an app on my local pc. THe frontend should be built with spinejs and the backend-api with node.js.
Spine is running on port 9294 and node.js is running on port 3000.
in Spine I've added to my model the following:



@url: http:localhost:3000/posts


and in my express server



app.get('/posts', function(req, res){
console.log(giving ALL the posts);
res.header(Access-Control-Allow-Origin, *)
res.json(posts);
});


But I'm always getting the following erro in chrome:



XMLHttpRequest cannot load http://localhost:3000/posts. Origin http://localhost:9294 is not allowed by Access-Control-Allow-Origin.


What must I do that I can access my api properly? I though adding the header in the responses does fix the problem.


More From » jquery

 Answers
20

app.get will only respond to GET requests. If the browser is preflighting it with an OPTIONS request, express will send an error because it doesn't have any listeners for those requests. Try adding this code in addition to yours and see if it works:



app.options('/posts', function(req, res){
console.log(writing headers only);
res.header(Access-Control-Allow-Origin, *);
res.end('');
});


Also note: if you're sending cookies with the request (withcredentials=true), then the Access-Control-Allow-Origin header cannot be *, it must be the exact value in the Origin header that the browser automatically adds to the ajax request like so:



res.header(Access-Control-Allow-Origin, req.headers.origin);


This is for security reasons - if you're doing something that requires cookies, then it is more likely that you will want to actually check that the origin is an allowed website in order to avoid CSRF attacks.


[#86354] Friday, April 6, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
ethanc

Total Points: 57
Total Questions: 111
Total Answers: 111

Location: Vanuatu
Member since Fri, May 13, 2022
2 Years ago
;