cors issue when integrated stripe payment gateway in reactjs - 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.

Related

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.

POST request to API created by lambda function in amazon AWS in python works good in postman but not in reactjs code

I have written the following code in my react js file, in the place of URL there is my AWS link.
const { empid, name, author } = body;
const onInputChange = e => {
setUser({ ...body, [e.target.name]: e.target.value });
};
const onSubmit = e => {
e.preventDefault();
axios.post(url, body);
history.push("/");
console.log(body);
};
This is my error I have already added Moesif origin crops extension to my browser :
Access to XMLHttpRequest at 'url' 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.
Check if the API has CORS disabled
Check if there a trailing / at the end of the api that you are calling. If there a trailing / then remove it. Ex: www.example.com/api/get_lists/ should be www.example.com/api/get_lists
You need to enable cors on your Api Gateway resource.
Also if you are using lambda proxy you need to return cors headers from your lambda response as well.
return {
statusCode: 200,
body: '<response as string>',
headers: {
'Access-Control-Allow-Origin': 'your allowed domains',
... // Other cors headers
}
}
Looks like that the CORS option is not enabled on your API Gateway Resource.
1 - Go to your API Gateway Resource and enable CORS.
2 - Re deploy your API Gateway for the changes to take effect.

ReactJS: access to fetch has been blocked by CORS policy

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

CORS issue in Axios

I'am Trying to get Data from another source via axios and it causes a CORS issue
if (imgUrl) {
axios
.get(proxyUrl + imgUrl, {
headers: {
"Access-Control-Allow-Origin": "*",
"Content-Type": "application/json",
},
})
.then((response) => {
console.log("response inside orderdetailPageCOntainer", response)
this.setState({binaryData: response.headers["x-final-url"]}, () =>
console.log("bbbbbbbb",this.state. binaryData));
});
// fetch(proxyUrl + imgUrl)
// .then(response => response.text())
// .then(contents => console.log("contents", contents))
// .catch(() => console.log(`Can’t access ${imgUrl} response. Blocked
by browser?`));
}
Follow these steps,
1) First check whether your Api is up.
2) Try to do the request via a postman tool. Cors do not apply for requests made via postman.
3) If the request is successful via postman, then you Api is good. Issue is cors.
4) Then add your front end app's domain as a allowed origin in you Api configuration. They way doing it depends on your Api technology. Read the doc on that.
5) there is no use of the the request Header: "Access-Control-Allow-Origin": "*". At the client side.
Hope this helps,
Cheers
Cross-Origin Resource Sharing (CORS) is a standard that allows a server to relax the same-origin policy. This is used to explicitly allow some cross-origin requests while rejecting others.
So maybe the other server rejecting loading resources from other domains.

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