Step 12

We are almost done with the QuickNote API. In anticipation of a common issue, in this section, we will add another middleware.

The Issue with CORS policy

If we were to run (or deploy) our QuickNote API and use it in a client application, the browser will block access to the API due to CORS policy.

Cross-Origin Resource Sharing (CORS) is an HTTP-header based mechanism that allows a server to indicate any origins (domain, scheme, or port) other than its own from which a browser should permit loading resources.

Since we intend to build a public API, we should add a header to our response, Access-Control-Allow-Origin: *, to allow requests from all domains. To understand how the fix works, go to Postman, run any requests, and notice 7 "header" attributes in the response.

Now, stop the API server and install the Node package cors

npm install cors

Next, update the /server/index.js file by importing cors

const cors = require("cors");

Next, linking it to express; this must be done before binding any of the route handlers!

app.use(cors());

That's it! Rerun the server and run any of the API requests in Postman. Make a note of the response header attributes:

The cors package adds this Access-Control-Allow-Origin: * to the header of every response we send back to the client. This information informs applications such as browsers that we allow cross-domain requests.

The cors package can take many options to allow, e.g., requests from specific domains (but not all). There are many resources online if you are interested to learn more about this. This short video could be a good starting point: Node API - CORS, what is it and how to use it on YouTube.