1

I'm building a nodejs server and I need to access more services using ajax from another domain, so how can I break the cross-domain restriction in nodejs code?

Note: Frameworks like ExpressJS is not an acceptable solution

Hazem Hagrass
  • 9,329
  • 10
  • 32
  • 54
  • All you really need to break the cross-domain access is the callback method approach. There is much documentation about it. JSONP I believe. http://en.wikipedia.org/wiki/JSONP – Leeish Jan 10 '14 at 23:43
  • Could you write an example for it in an answer? – Hazem Hagrass Jan 10 '14 at 23:44
  • Close your question. Here is a complete answer: http://stackoverflow.com/questions/3506208/jquery-ajax-cross-domain – Leeish Jan 10 '14 at 23:44
  • Essentially all you are doing is forcing the consumer to setup a function on their end to handle the request. – Leeish Jan 10 '14 at 23:45
  • but this is not a nodejs solutions, this post is for php – Hazem Hagrass Jan 10 '14 at 23:46
  • The JSONP link at the top of the answer explains JSONP with documentation. It's all done via javascript. Nothing really special to do server side. – Leeish Jan 10 '14 at 23:46
  • 1
    @Leeish With all respect, your reply is incomplete. JSONP only works when the server supports it. A better, modern solution would be CORS. – Rob W Jan 11 '14 at 00:14
  • 1
    @HazemHagrass Do you need to offer cross-domain access of third-party websites via your server? If so, then take a look at https://github.com/Rob--W/cors-anywhere. It's a reverse proxy that enables CORS on proxied requests, written in Node.js. – Rob W Jan 11 '14 at 00:20

1 Answers1

-1

Generally speaking, when there is a cross domain restriction in effect you have two possible options to take.

  1. Determine if the remote party you're trying to talk to supports CORS. Have them allow your domain on their end in the HTTP headers. Sometimes this is not possible.

  2. Setup a reverse HTTP proxy that allows you to communicate to the remote party but goes through your web server first so you bypass the cross domain origin security issue. Node-http-proxy is a possible solution if you're already using Node.js

CORS is generally only supported in more recent browsers, so if you have a requirement to support old stuff that might not be suitable.

Note in jQuery from linked resource.

$.support.cors

boolean will be set to true if the browser supports CORS

Steve
  • 1,423
  • 10
  • 13