Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what does app.use(cors()) do?

I know that we cannot have access to an API that has different domain there ours. However, I see many people installing the cors module in express to use APIs and then using it like so:

app.use(cors());

What does it actually do? How does this function enable cors on the server?

like image 984
Jeff Goes Avatar asked Sep 03 '17 14:09

Jeff Goes


1 Answers

Abstract

As you said, it enables CORS (cross-origin resource sharing). In order for your server to be accessible by other origins (domains).

What it really does

Calling use(cors()) will enable the express server to respond to preflight requests.

A preflight request is basically an OPTION request sent to the server before the actual request is sent, in order to ask which origin and which request options the server accepts.

So CORS are basically a set of headers sent by the server to the browser. calling cors() with no additional information will set the following defaults:

{
  "origin": "*",
  "methods": "GET,HEAD,PUT,PATCH,POST,DELETE",
  "preflightContinue": false,
  "optionsSuccessStatus": 204
}

these are translated into these headers:

Access-Control-Allow-Origin: *
Access-Control-Allow-Methods: GET,HEAD,PUT,PATCH,POST,DELETE
Status Code: 204

What is this doing is basically making your server accessible to any domain that requests a resource from your server via a browser.

you can check all the express cors configurations here: https://github.com/expressjs/cors

you can also read more about browser cors here: https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS

like image 68
Bamieh Avatar answered Oct 23 '22 13:10

Bamieh