Failed to upload data from heroku app. CORS error - reactjs

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).

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.

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 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.

fetching express back-end with react return 405 error (from origin 'null' has been blocked by CORS policy: Response to preflight etc...)

I have a small express/react app. I'm running server side on port 5000 and client side on port 3000. I have the following component on the front-end:
componentDidMount() {
fetch('http://localhost:5000/auth/google',
{
method: 'GET',
headers: {'Content-Type': 'application/json'},
credentials: 'same-origin',
'Access-Control-Allow-Origin': '*'
})
.then(res => {
if (!res.ok) {
throw res;
}
return res.json()
}).then(data => {
this.setState({loading: false, data});
}).catch(err => {
console.error(err);
this.setState({loading: false, error: true});
});
}
on the back-end I have this:
router.get(
"/auth/google",
passport.authenticate("google", { scope: ['Profile','https://www.googleapis.com/auth/analytics.readonly'] })
);
router.get(
"/auth/google/callback",
passport.authenticate("google", { failureRedirect: "/error", session: false }),
function(req, res) {
var token = req.user.token;
request('https://www.googleapis.com/analytics/v3/management/accounts?access_token=' + token,
function (error, response, body) {
console.log(JSON.parse(body).items);
res.send(JSON.parse(body).items)
});
}
);
and here are the error I have:
Failed to load resource: the server responded with a status of 405 ()
and
Access to fetch at 'https://accounts.google.com/o/oauth2/v2/auth?response_type=code&redirect_uri=http%3A%2F%2Flocalhost%3A5000%2Fauth%2Fgoogle%2Fcallback&scope=Profile%20https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fanalytics.readonly&client_id=blablabla.apps.googleusercontent.com' (redirected from 'http://localhost:5000/auth/google') from origin 'null' 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.
CORS security violation is triggered by your browser which:
has got React code (presumably script bundles) from one server,
is seeing attempts by this code to fetch from another server that is not telling the browser to calm down and tolerate this security violation.
Failed to load resource: the server responded with a status of 405
This means the browser attempted to contact 'another server' prior to fetch and ask if it should tolerate the security violation but 'another server' refused to talk. Technically speaking, the browser has sent HTTP request using HTTP verb OPTIONS and the server responded by indicating it doesn't support this verb.
Access to fetch at 'https://accounts.google.com/o/oauth2/
That's the actual CORS violation detected by the browser which effectively refused to execute fetch.
There are lots of recipes how to calm down the browser so that it would tolerate CORS violations. But the best apprroach is to ensure the violations won't happen so that there is no need to relax the security.
The output of a React application build are .html files and script bundles, possibly source maps. Called build artifacts. If you structure your project so that in both development and production the browser gets everything (build artifacts, API responses) from one single source e.g. Express then there will be no room for CORS issues.

Fetch API cannot load, cors

In my React app I am trying to make a GET request from my heroku server to get a list of users:
https://blablabla.heroku.com/users
using the following request:
const sendSearch = fetch('/https://blablabla.heroku.com/users', {credentials: 'same-origin'})
function loadMyUsers(data) {
data.json().then((jsonData) => {
// console.log(jsonData)
})
}
sendSearch.then(loadMyUsers)}
However I get the following error:
Fetch API cannot load https://blablabla.heroku.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:8080' 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.
I tried changing my Fetch method to many things similar to:
const sendSearch = fetch('https://blablabla.heroku.com/users',{
method: 'GET',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
'mode': 'no-cors'
}
})
but the problem persists.
How do I make the cross domain request?
On your heroku server you should add Access-Control-Allow-Origin: * to your response headers, or more specific Access-Control-Allow-Origin: http://localhost:8080 if you wish.
On your production server though, you probably won't need this header, unless you have very good reason for cross origin requests.

Resources