What is CORS? How to deal with it, and why is there no error in Postman?
Cross-Origin Resource Sharing (CORS) is a security feature inside browsers which prevent you from making HTTP requests to websites of another origin.
What is CORS?
Cross-Origin Resource Sharing (CORS) is a security feature inside browsers which prevent you from making HTTP requests to websites of another origin.
Let’s say your website runs on localhost:3000 and you want to make a request to example .com. By default, your browser prevents you to make any HTTP request to this domain.
Note: Even different ports are considered different origins. If you make request to localhost:8000 from localhost:3000, it is still considered a cross-origin request.
How it works
When you make a HTTP request to a different domain (cross-origin request), the server receives it and processes the data as usual.
In the response headers, the browser checks for CORS headers. If the headers allow the request to made from different domain, the browser let’s the client side JavaScript access the response.
But if there are no CORS headers or if the CORS headers does not allow request to be made from your origin, the browser does not let you access the response in your JavaScript and you get a CORS error in your console.
For some requests, browser sends a preflight request using the OPTIONS HTTP method to ask the server for information if the requests should be made or not. If there are appropriate CORS headers in the response, the browser makes the request and lets you access response data in JavaScript.
CORS headers
There are 2 main CORS headers:
Access-Control-Allow-Origin header specifies which origins are allowed to access the resource. A wildcard (*) means any client can access the resource. Or there can be specific origins which have access to the resource.
Access-Control-Allow-Methods header specifies what all HTTP methods (GET, POST, PUT, DELETE) are allowed.
Why does it work on Postman?
This is a very common question. Why does CORS error show in my browser but when I make the same request in Postman, it works.
As I mentioned earlier, the CORS is a browser policy. The browser is not letting you access the resource for safety, it is not the server denying the request.
How do you solve it?
If you have access to the server code, you have to add appropriate CORS headers to allow different origins to access your resources from browsers. You can either add them manually, or use a cors library if you are using express for the backend.
If the server code is not in your hands, then you can’t technically enable cross-origin requests. But one hack is to use a proxy like https://cors.sh/. You have to add the website you want to make request to in the link. This will make request on behalf of you. Since they will not be requesting from a browser, it will work.
Example: https://cors.sh/https://example.com