CORS in NodeJS without the use of Frameworks

10

I'm creating an application in Phonegap and consuming an API provided through NodeJS. For this to happen, I need NodeJS to accept CORS.

How do I enable CORS so that NodeJS accepts the request?

    
asked by anonymous 15.02.2014 / 06:26

3 answers

13

Enabling CORS is a simple matter of adding header Access-Control-Allow-Origin to your response. In node.js, this is done using the response.setHeader method:

response.setHeader("Access-Control-Allow-Origin", "*"); // Permite qualquer site fazer
                                                        // requisições Ajax no seu servidor

or:

response.setHeader("Access-Control-Allow-Origin", "http://example.com"); // Domínio(s)
response.setHeader("Access-Control-Allow-Origin", "http://example.net"); // específico(s)

This answer in SOEN has more details if you need to. To look at the options that CORS offers (including the other headers you may want to add) I suggest this tutorial (note: in English). In summary:

  • Access-Control-Allow-Credentials : causes cookies to be passed along with a CORS request (by default, they are not);
  • Access-Control-Expose-Headers : Allows the code making the CORS request to access other types of headers besides the most common ones.
15.02.2014 / 06:40
5

In addition to @mgibsonbr, on response.setHeader("Access-Control-Allow-Origin", "*"); and Access-Control-Allow-Credentials , if you make requests other than GET, such as POST, PUT, DELETE, or even some custom method, you will define one or two additional headers.

Both the reference in HTML5Rocks and a second question just below the aforementioned @mgibsonbr commented on. I make a point of commenting here because it already gave me a huge headache when working with phantomjs and random errors with unclear error messages.

Access-Control-Allow-Methods

For methods other than GET, it will be mandatory for the server to tell which methods it supports, something like

res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');

//res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS');

If you have errors, also add OPTIONS. In some very complicated situations, debugging your browser may make an OPTIONS request before the request that it was actually requested to do.

Access-Control-Allow-Headers

In addition, if you use some unusual header, it is interesting that your server responds that such header can be used.

res.header('Access-Control-Allow-Headers', 'Content-Type, X-Custom-Header');

Because some types of headers can be used maliciously, browsers may block you from sending a header out of the ordinary. Rejecting an XMLHttpRequest object and accidentally sending an unwanted header will cause error. Be careful about that.

Debug

It's worth using Postman ( link ) to debug your tests. It is very intuitive and flexible. Another tool that is handy on the wheel is to use cURL when to inspect the raw response of your server.

If you still have problems, be sure to leave your NodeJS server logging ALL requests to see if your application is not doing something implicit, such as an OPTIONS request, and you have an error message that is not clear.

    
15.02.2014 / 08:14
1

You can use the middleware link to enable CORS support easily and quickly.

    
27.02.2014 / 00:12