Cors
--
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’
The error clearly states you are violating the policy as there is no header present.
Example (node 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 sayingfetch(url,{crednetials:true})
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 iftrue
, ignores or blocks iffalse
- 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 wheretrue
this will pass on the preflight information to the next handlerfalse
this won't allow the preflight information to the next handler
Explained a few of the methods that I have come across and used extensively.
We can also look at the document in the link.
References:
Used: