ReactJS: access to fetch has been blocked by CORS policy - reactjs

I am getting the following error in my ReactJS project:
"access to fetch has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource
If an opaque serves your need set the request mode to 'no-cors' to fetch the resource with CORS disabled."
This is how I send requests to the backend:
export const sendRequest = async ( endpoint = '' ,
method = 'GET', body) => {
const response = await fetch(`${url}${endpoint}`, {
method,
headers: { "Content-Type": "application/json" },
body: JSON.stringify(body)
})
const data = await response.json();
return data;
}
I thought first that it is a backend problem but I checked there, found backend CORS Access is enabled for the same headers and client.
Any modifications should I do to the function above??

There an npm module called cors. You can install it in your backend. If you are using ExpressJS, you can just use cors as an middleware using app.use(cors()). With the equivalent header set in the request, it should work

Related

How do i enable cors policy / or request in react js with no access to the API?

Im using RapidApi to make som simple calls for fetching country data using axios. The API is paged in that the next response will have the URL for the next request. So basically i don't even have the URLs.
Problem i get the error which i have seen all over stack overflow about cors policy
Access to XMLHttpRequest at 'https://api.hybridgfx.com/api/list-countries-states-cities?page=2' from origin 'http://localhost:3002' 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.
I tried adding the line "access-control-allow-origin": "*" but that doesn't work and i still get the same error. When i click on the URL or just run it directly on the browser i get a bunch of data but when it is called in the code it blows up . Please help.
const fetchNextResults = async (url: string): Promise<FetchResponse> => {
const options = {
method: "GET",
url: url,
headers: {
"X-RapidAPI-Key": MyKey,
"X-RapidAPI-Host": "countries-states-cities-dataset.p.rapidapi.com",
"access-control-allow-origin": "*",
},
};
const res: FetchResponse = await axios
.request(options)
.then(function (response) {
console.log(response.data);
return response.data;
})
.catch(function (error) {
console.error(error);
});
return res;
};
You can send a request throw the CORS proxy.
List of proxies.
url: <proxy url>/<my url>
Or create your own.

How to handle CORS Policy when use fetch function on ReactJs

need help for ReactJs. I still learning reactJs to fetch data from PHP backend. I'm using Xampp as my local server. but when i integrate fetch function on ReactJs, i got CORS policy error.
here is my code from on my App.jsx
useEffect(() => {
fetch("http://localhost:81/opencart/index.php?route=api/create", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ items: [{ id: "xl-tshirt" }] }),
})
.then((res) => res.json())
.then((data) => setClientSecret(data.clientSecret));
}, []);
On my reactJs package.json file i added this
"proxy": "http://localhost:81/"
but still display error on browser console
Access to fetch at 'http://localhost:81/opencart/index.php?route=api/create' from origin 'http://localhost:3000' 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.
How do I resolve this?
CORS issue is definitely coming from Server. So the ideal way is to set your server to accept your request from cross origin.
Seems you are working with server built with PHP, then check your backend server to add CORS configuration.
For Express.js and others are having several way to add it such as adding 'cors` middleware.

Can't fetch API from React application

I have built API in Google Cloud Function. The CORS error occurs when I try to fetch API directly. Although I added Access-Control-Allow-Origin, it failed.
The error:
'https://xxxxxxx.com' from origin 'http://localhost:3000' 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.
const apiURL = 'https://xxxxxxx.com'
const headers = new Headers();
headers.set("Content-type", "application/json");
headers.set("Access-Control-Allow-Origin", "*");
const createRes = await fetch(
`${apiURL}/testFetch`,
{
method: "POST",
headers: headers,
body: JSON.stringify({
test: "test"
}),
}
);
Access-Control-Allow-Origin is a response header. It should be a part of your response, not the request. Please ensure that your API returns the corresponding header.
https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Origin

cors issue when integrated stripe payment gateway in reactjs

I am trying to integrate stripe payment gateway in my react project but cors related issue occur.
Can any one help me to resolve this.
"Access to fetch at 'https://connect.stripe.com/oauth/token' from origin 'http://localhost:3000' 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."
But it works fine when I am disabling the cors in chrome browser. Is there any alternate how to integrate stripe payment gateway in reactjs project?
My code:
const bodyFormData = new FormData()
bodyFormData.append("client_secret", "");
bodyFormData.append("code", code);
bodyFormData.append("grant_type", "authorization_code");
fetch("https://connect.stripe.com/oauth/token", {
method: 'POST',
body: JSON.stringify(userData),
headers:{
Accept:'application/json',
'Content-Type': 'application/json; charset=utf-8',
'Access-Control-Allow-Origin':"*",
OPTIONS: '',
}
})
.then((response) => response.json())
.then((res) => {
console.log(res);
resolve(res);
})
.catch((error) => {
reject(error);
});
It looks like you're making that call to complete the connection from frontend React code in a browser. You can't do that and it will never work, since it uses your Stripe secret key which should never be on the frontend.
Instead you should make this call from a backend server route after the user is redirected from the OAuth page.

Failed to upload data from heroku app. CORS error

I'm trying to fetch my data from a heroku app into Redux, but I think I'm running into a CORS issue. I've been playing with "headers" for a while and still can't figure it out.
This is the exact error:
"Failed to load https://name-app.herokuapp.com/users: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled."
And this is my code:
export function fetchMicros() {
return dispatch => {
const url = "https://name-app.herokuapp.com/users";
return fetch(url, {
method: 'GET',
mode: 'cors',
headers: { 'Content-Type': 'text' },
})
.then(handleErrors)
.then(res => res.json())
.then(micros => {
dispatch(fetchVitamins(micros));
}
)};
};
If you don't have to do any authentication nor need to pass any data, you can do a no-cors request (more information on mdn page).
fetch(url, {
mode: 'no-cors',
})
If you do need cookies or some kind of authentication, then you need to make the server accept your domain and request methods on the preflight response.
In the event that you don't have access to change that on the server, you can create a nodejs server that will handle the calls for you, bypassing any cors checks (only browser cares about cors, servers don't).

Resources