0

I'm following a simple tutorial from here:

http://addyosmani.github.io/backbone-fundamentals/

I have a node.js server running on a localhost port 4711

I have tomcat running on port 8082 and a backbone.js app as client started as index.html on that server.

But I get :

XMLHttpRequest cannot load ... api/books. Origin localhost:8082 is not allowed by Access-Control-Allow-Origin.

1) Why? This is not file based access - indeed a plain web browser will see

htttp://localhost:4711/ and interact just fine.

2) What's the fix? (Given that part of this stack is a node.js server)

Tony Eastwood
  • 781
  • 2
  • 9
  • 23

1 Answers1

1

You're initiating a CORS request since the two servers are listening on different ports( index.html on localhost:8082 and your node server on localhost:4711)

In your node's http server, try setting the Access-Control-Allow-Origin header to * or to the Origin header.

http.createServer(function(req, res) {
    res.header('Access-Control-Allow-Origin', req.headers['origin']);
    //handle
});
c.P.u1
  • 16,664
  • 6
  • 46
  • 41
  • Thanks for quick answer. So is this standard practice when using node.js ? (Because each node.js going to have its own port number.) Or could somehow I persuade my Tomcat server to server data from node.js? – Tony Eastwood Oct 21 '13 at 12:40
  • Whenever you need to perform an Ajax request to a domain different than the origin domain, you use `CORS`. This is not specific to `node.js` and can be used on any other server as well. – c.P.u1 Oct 21 '13 at 13:55
  • I'm a little confused here. Do I need to alter both client and server (node js) code or is something that can be done from one side only. Is there a definitive answer anyone can point me to for a Backbone client and Node.js server. – Tony Eastwood Oct 21 '13 at 16:38
  • I found this answer to be the most useful. This allows one to do everything from the NODE.js side. There are other approaches using horrid jquery magix on the client side - I would avoid those! http://stackoverflow.com/questions/16046364/origin-http-localhost-is-not-allowed-by-access-control-allow-origin/16046714#16046714 – Tony Eastwood Oct 22 '13 at 11:09