CORS with Express
Updated: 03 September 2023
There are two parts to making a response, the request and the response
We need to handle CORS
on each end
Browser
In the browser, we can make cross-origin requests using fetch
with mode:no-cors
which will make an opaque response which has some limitations
Now, sure that’s great and all when using a 3rd party API, however as mentioned there are limitations to the response object that is received. We can compare this to a API that has CORS enabled
Note that this response has a lot more data included
Node.js
When using express
we simply need to set the response header to enable CORS. We can do this using a simple middlewear, in this case a simple function which takes in an array of origins (or even a single origin) and returns a cors
middlewear function
cors.js
In our main express file we can use this in one of two ways
We can either choose to allow all origins by default *
server.js
Or only allow specific origins: