i got an error when trying to access some API from web called rajaongkir api it shows an error 400 and no access control origin. it's need a header 'key' to work i already test it on postman and it works well. please help me
Code:
componentDidMount(){
const key = {
method: 'GET',
headers: { 'key': '11sss8ba9eeb9e4845c01edc3e62e62b80b', 'content-type': 'application/json' },
url: 'https://api.rajaongkir.com/starter/province'
}
axios(key).then(response => {
this.setState({ provinsi: response.data.results });
}).catch(error => {
console.log(error)
})
}
error:
Failed to load resource: the server responded with a status of 400 (Bad Request)
:8000/#/profil:1
Access to XMLHttpRequest at 'https://api.rajaongkir.com/starter/province' from origin 'http://127.0.0.1:8000' 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 have tried allowing origin access and it's just removing the No "access-control.." but still got blocked by cors policy
install Allow CORS: Access-Control-Allow-Origin extension in the browser
https://chrome.google.com/webstore/detail/allow-cors-access-control/lhobafahddgcelffkeicbaginigeejlf?hl=en
Related
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.
Why I got this first CORS and then Post request auto turn into OPTION,
I run this on my local with just button click , When first I get the CORS I added header as well you can see in below code.
var postData2= {
"input_text": "انسان سب سے بڑی غلطی اس وقت کرتا ہے جب وہ اللہ کی طرف سے دی گئی ڈھیل کو اس کا کرم سمجھنے لگتا",
"output_lang": "ENG",
"name": "zahid",
"contact": "4646468"
}
console.log(postData2);
let axiosConfig = {
headers: {
'Content-Type': 'application/json;charset=UTF-8',
"Access-Control-Allow-Origin": "*",
}
};
axios.post('http://95.217.98.30:8000/u2r/convert', postData2 , axiosConfig)
.then((res) => {
console.log("RESPONSE RECEIVED: ", res);
})
.catch((err) => {
console.log("AXIOS ERROR: ", err);
})
I got this error in my console
Access to XMLHttpRequest at 'http://95.217.98.30:8000/u2r/convert' 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.
Nothing wrong with your code. It's a browser level security enabled to restrict the response being received from other domains. Though you add "Access-Control-Allow-Origin": "*" in your request header, it will not resolve your problem. The same header should be added to your response header. This should be done from your server-side code. Please go through the below page to implement it in your server-side.
https://enable-cors.org/server.html
I have a problem on my next.js app.
I try to make a get request from the client side on this endpoint:
https://fr.pornhub.com/webmasters/search
when the request is made on back side all work but when she is send from client i get cors error
The problem is if I try to make it like that
return
fetch('http://www.pornhub.com/webmasters/search?page=2', {
headers: {
// 'Access-Control-Allow-Origin': '*',
},
})
.then((r) => r.json())
.then((data) => {
console.log(data);
return data;
});
I get this error:
'Access to fetch at 'http://www.pornhub.com/webmasters/search?page=2'
from origin 'http://localhost:3000' has been blocked by CORS policy:
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.'
And if I uncomment Access-Control-Allow-Origin this I get this one:
'Access to fetch at 'http://www.pornhub.com/webmasters/search?page=2'
from origin 'http://localhost:3000' has been blocked by CORS policy:
Response to preflight request doesn't pass access control check:
Redirect is not allowed for a preflight request.'
If I understand goodly I can't use options on this endpoint but I cannot add Access-Control-Allow-Origin without option preflight?
So how resolve that?
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.
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).