Skip to content Skip to sidebar Skip to footer

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 lik

Solution 1:

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,DELETEStatus 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

Post a Comment for "What Does App.use(cors()) Do?"