CORS — Cross-Origin Resource Sharing

We have dealt with this almost every time. The issue originates when one domain requests the resource for another domain.

Local Setup:

Here is a simple error where ‘http://localhost:3000/items’ is being accepted by the request from the ‘http://localhost:1234’

Image Courtesy: Internet

The error clearly states you are violating the policy as there is no header present.

Example (node js):

Local server.js

If any domain access this application using an AJAX call or from XHR from the UI (which is in a different domain), the cors error is likely to happen.

Fix (using the npm package):

we can use the cors library from the npm package manager.

Now here we can put the origin as ‘*’ which specifically tells that any domain can allow the requesting service.

So ideally if we try hitting “http://localhost:3009/data” we will be seeing the data something like this in the below image.

CORS (npm package):

Cors also accepts numbers of options to be passed

  • Credentials:
    Here consider the server is being called with the user credentials (be it login, cookies, tokens, etc) then on the fetch or the XHR request we will saying
    so just by this above the request coming to the server will contain the credentials being picked from the requesting source.
    Now in server, we will need to enable these credentials in the cors by
    Allows if true , ignores or blocks if false
  • Allowed Methods:
    Here we can also start passing the allowed request the domain can accept.
    This accepts the methods in the form of arrays.
  • Preflight Request:
    This accepts a boolean value where
    true this will pass on the preflight information to the next handler
    false this won't allow the preflight information to the next handler



Tech Stuff

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store