Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

For what reason I can access the resources by curl, but not in the browser?

Tags:

cors

On the server side I'm using Rails. Purposely, I did not configure the CORS. Thus, as I expected, in the browser I can not do requests to the Rails server because I get this error:

enter image description here

But I can do for the terminal, using curl:

macabeus@macabeus-acer ~ $ curl http://localhost:3000/people
[{"id":3,"name":"macabeus","age":20,"created_at":"2016-07-31T22:45:05.490Z","updated_at":"2016-07-31T22:45:05.490Z"},{"id":4,"name":"foo","age":10,"created_at":"2016-07-31T22:45:24.415Z","updated_at":"2016-07-31T22:45:24.415Z"}]

For what reason the curl can, but the browser can't? I know how to solve this problem. I just want to understand what I asked earlier.

like image 537
macabeus Avatar asked Jul 31 '16 23:07

macabeus


1 Answers

The difference should be whether the header Origin: http://... is sent in the request or not. curl by default doesn't send any extra headers, which you can confirm by running curl with -i option:

$ curl -i http://localhost:3000/people

If you send any arbitrary value in the Origin header along with the request like:

$ curl -i -H 'Origin: http://localhost:63343' http://localhost:3000/people

you should then see the same CORS error as in the browser.

The reason behind this is that the header Origin triggers if the request is a CORS one, i.e. comes from a different site, and depending on the configuration on the server side no Origin header may mean it comes from the same origin.

like image 71
Tadayoshi Sato Avatar answered Jan 12 '23 19:01

Tadayoshi Sato