Do want to make some HTTP request to some enpoint but not able to make because of Browser feature, which is called CORS.
CORS, or Cross-Origin Resource Sharing, is a security feature implemented by web browsers to control how resources on a web page can be requested from another domain outside the domain from which the resource originated.
Example:
My domain is localhost:3000 and Other domain is api.example.com . So now if i want to make a request from my local server to other server which have different domain. Then a flow of CORS request will started.
Flow of CORS request :
1. Initial Request:
You (the client) attempt to make a request to a resource (like an API endpoint) located on a different domain (let’s call it https://api.example.com) from the domain of your current page eg.( localhost:3000 ).
2. Preflight Request:
Condition: If your request is considered a “complex request” by the browser, meaning it uses methods other than GET, HEAD, or POST, or it includes headers other than simple headers (like Content-Type), the browser will automatically initiate a preflight request.
Preflight Request: The browser sends an HTTP OPTIONS request to the server (https://api.example.com) to determine if the actual request (e.g., POST, PUT, DELETE) is safe to send. This preflight request includes headers such as Origin, Access-Control-Request-Method, and Access-Control-Request-Headers.
– Server Response: The server (https://api.example.com) must respond to this preflight request with appropriate CORS headers:
– Access-Control-Allow-Origin: Specifies which origins are allowed to access the resource (* for all, or specific domains like https://www.yourwebsite.com).
– Access-Control-Allow-Methods: Lists the allowed HTTP methods for accessing the resource (GET, POST, PUT, etc.).
– Access-Control-Allow-Headers: Lists the allowed headers that can be used in the actual request.
The preflight request ensures that potential cross-origin requests are safe and authorized before the actual data exchange occurs, maintaining security and integrity on the web.
3. Actual Request (if approved):
Condition: If the server responds to the preflight request with appropriate CORS headers and indicates that the actual request is allowed (Access-Control-Allow-Origin includes the origin of your request and any required methods/headers are allowed), then the browser proceeds to send the actual request (e.g., POST, PUT, DELETE) to https://api.example.com.
Which means that https://api.example.com server is allowing you to make that request and you can access that.
– Server Response: The server (https://api.example.com) processes the request and sends back the response.
4. Handling Responses:
Success: If the server responds with a successful status (e.g., 200 OK), the browser allows your client application to access the response data.
Error: If there are CORS-related errors (e.g., mismatch in allowed origin, methods, or headers), the browser blocks the response data from being accessed by your client application, adhering to the same-origin policy.
Solution of CORS error :
So because of browser built-in security feature we are not able to make a request on different domain. But we can bypass this using plugin and some extensions but that not right approach, it can break the security of browsers and sometimes these things not work well.
Now for developer community i made something interesting which is called cors-handler. It basically act as a proxy sever and will make request on give url path or domain which you want to access. It will not give you any kind of CORS related errors because in our server setting configuration we are allowing all the origins to access our services.
Now you don’t have to make direct HTTP request to another domain or path-url to access something, use our path-url to access another domain :
“https://handler-cors.vercel.app/fetch“
Note: I’m helping the developer community and no any charges will be taken from you. It is a free service and I’ll maintain it for you guys.
How to use cors-handler??
Make sure that you use right endpoint which is /fetch, make POST request and also send a url key field in body object with its value.
We have provided some example using fetch and axios in these examples you just have to change the “https://www.example.com/api/endpoint” with right url which you want to access.
You can use any approach from given examples:
– Using fetch
//Define an async function to make the POST request async function getData() { try { const res = await fetch("https://handler-cors.vercel.app/fetch", { method: "POST", headers: { "Content-Type": "application/json", }, body: JSON.stringify({ url: "https://www.example.com/api/endpoint", //Replace this example url with right url which you want to access }) }); if (!res.ok) { throw new Error(`Error: ${res.status} ${res.statusText}`); } const raw = await res.json(); console.log(raw); // see raw in console } catch (error) { console.error("Error fetching data:", error); } } getData(); //calling the function
– Using axios
const axios = require('axios'); // install axios or use can use CDN Link of it // Define the data to be sent const bodyData = { url: 'https://example.com/api/endpoint', //Replace this example url with right url which you want }; // Define the config with headers const config = { headers: { 'Content-Type': 'application/json', } }; // Define an async function to make the POST request async function getData() { try { const response = await axios.post("https://handler-cors.vercel.app/fetch", bodyData, config); console.log('Response:', response.data); } catch (error) { console.error('Error:', error); } } getData() // calling the function
6 Comments
You are a savior brother, Thanks a Lot !!!
For Explaining and also giving a way to bypass it.
This is awesome!! Thank you so much!! Have been struggling with this for a long time!
This is very interesting, You’re a very skilled blogger. I have joined your rss feed and look forward to seeking more of your wonderful post. Also, I’ve shared your site in my social networks!
Very interesting subject, regards for putting up. “I do not pretend to know where many ignorant men are sure-that is all that agnosticism means.” by Clarence Darrow.
Thanks for sharing. I read many of your blog posts, cool, your blog is very good.
priligy in usa He said it was more like a family crush like he had feelings as in he wanted nothing bad to happen to me, she wrote