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?
As you said, it enables CORS
(cross-origin resource sharing). In order for your server to be accessible by other origins (domains).
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With