Step 5

Recall the issue with CORS (Cross Origin Resource Sharing) when we were working with the SIS API. The browser blocked our access to the SIS API due to CORS policy. We needed to install a plugin to get around this issue. At the time, I've noted this is an issue on SIS API's side. They must update their responses to include Access-Control-Allow-Origin: * in their HTTP header to allow requests from all domains. This will be the case for our YouNote API as well. Since the intention is to build a "public" API, we must allow cross domain requests.

The fix happens to be very simple, as long as we are working with NodeJS & Express. To understand how the fix works, go to Postman, run any of the requests, and notice in the response, there are 6 "header" attributes.

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

npm install cors

Next, update the index.js file by

  1. Importing cors

    const cors = require("cors");
    
  2. Linking it to express

    app.use(cors());
    

That's it! Run the server again and run any of the API requests in Postman. Make 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 browsers that we allow cross domain requests.

The cors package can take many options to e.g. allow requests from certain 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.