DEV Community

Derick Makuto Simiyu
Derick Makuto Simiyu

Posted on

How do I resolve react cors error!

I'm really having difficulty to fix cors error on an app developed in react. The error snippet below from browser console:

Access to fetch at 'https://thingproxy.freeboard.io/fetch/https://api.yelp.com/v3/businesses/search?term=fish&location=phoenix&sort_by=best_match' from origin 'https://bitepoint.link' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

My fetch api code below:

const apiKey = "xxx";

const Yelp = {
search(term, location, sortBy) {
    return fetch( https://thingproxy.freeboard.io/fetch/https://api.yelp.com/v3/businesses/searchterm=${term}&location=${location}&sort_by=${sortBy},
{
// crossDomain: true,
// mode: "cors",
// method: "GET",
// credentials: "include",
// "Access-Control-Allow-Credentials": true,
// "Access-Control-Allow-Methods": "GET",
headers: {
Authorization: Bearer ${apiKey},
},
}
).then((response) => {
return response.json();
}).then((jsonResponse) => {
if (jsonResponse.businesses) {
return jsonResponse.businesses.map((business) => {
//console.log(business);
return {
id: business.id,
imageSrc: business.image_url,
name: business.name,
address: business.location.address1,
city: business.location.city,
state: business.location.state,
zipCode: business.location.zip_code,
category: business.categories[0].title,
rating: business.rating,
reviewCount: business.review_count,
};
});
}
});
},
};

Top comments (2)

Collapse
 
jwhenry3 profile image
Justin Henry

This is fine if you are good with third parties having access to your traffic and payloads. Might want to invest in a NextJS or slim NodeJS in-house proxy to facilitate your needs. The concept is the same, just changing the domain you're hitting and do a passthrough from the server to hit the other server. Server-side REST calls are not subject to CORS. Why does this matter in the browser? Because arbitrary insecure code can run on the client, its significantly less likely (near impossible) to happen on the server.

Collapse
 
cevin77 profile image
Cevin77

wow!