Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't adding CORS headers to an OPTIONS route allow browsers to access my API?

I am trying to support CORS in my Node.js application that uses the Express.js web framework. I have read a Google group discussion about how to handle this, and read a few articles about how CORS works. First, I did this (code is written in CoffeeScript syntax):

app.options "*", (req, res) ->   res.header 'Access-Control-Allow-Origin', '*'   res.header 'Access-Control-Allow-Credentials', true   # try: 'POST, GET, PUT, DELETE, OPTIONS'   res.header 'Access-Control-Allow-Methods', 'GET, OPTIONS'   # try: 'X-Requested-With, X-HTTP-Method-Override, Content-Type, Accept'   res.header 'Access-Control-Allow-Headers', 'Content-Type'   # ... 

It doesn't seem to work. It seems like my browser (Chrome) is not sending the initial OPTIONS request. When I just updated the block for the resource I need to submit a cross-origin GET request to:

app.get "/somethingelse", (req, res) ->   # ...   res.header 'Access-Control-Allow-Origin', '*'   res.header 'Access-Control-Allow-Credentials', true   res.header 'Access-Control-Allow-Methods', 'POST, GET, PUT, DELETE, OPTIONS'   res.header 'Access-Control-Allow-Headers', 'Content-Type'   # ... 

It works (in Chrome). This also works in Safari.

I have read that...

In a browser implementing CORS, each cross-origin GET or POST request is preceded by an OPTIONS request that checks whether the GET or POST is OK.

So my main question is, how come this doesn't seem to happen in my case? Why isn't my app.options block called? Why do I need to set the headers in my main app.get block?

like image 766
mikong Avatar asked Aug 15 '11 16:08

mikong


People also ask

How do I enable CORS on my browser?

To enable cross-origin access go to Tools->Internet Options->Security tab, click on “Custom Level” button. Find the Miscellaneous -> Access data sources across domains setting and select “Enable” option.

How do I fix the CORS problem in my browser?

Cross-Origin Resource Sharing (CORS) errors occur when a server doesn't return the HTTP headers required by the CORS standard. To resolve a CORS error from an API Gateway REST API or HTTP API, you must reconfigure the API to meet the CORS standard.


1 Answers

I found the easiest way is to use the node.js package cors. The simplest usage is:

var cors = require('cors')  var app = express() app.use(cors()) 

There are, of course many ways to configure the behaviour to your needs; the page linked above shows a number of examples.

like image 102
Wayne Maurer Avatar answered Sep 18 '22 13:09

Wayne Maurer