CORS errors on Axios Graphql query - reactjs

I'm trying to use react-axios to query a graphql endpoint but I'm encountering a problem with CORS.
Access to XMLHttpRequest at 'https://rickandmortyapi.com/graphql' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
Here it is my setup:
const characterQuery = `{
characters(page: 2, filter: { name: "rick" }) {
info {
count
}
results {
name
status
species
gender
image
}
}
}`
const axiosInstance = axios.create({
data: characterQuery,
headers: {"Access-Control-Allow-Origin": "*"}
})
<AxiosProvider instance={axiosInstance}>
<Post url="https://rickandmortyapi.com/graphql">
{(response: any) => {
console.log(response);
}}
</Post>
</AxiosProvider>
Can someone help me? Thanks

CORS is a pain, always, the problem is that the header you pass is the one the server should give you.
You can't force the server to pass the header if they don't already, that the whole point of this protection, avoiding hacker pretending to be other ppl websites.
So the API you are trying to reach must have the CORS header or it will not work
You can play around with fetch see if you have better luck than axios.
Fetch provide some amount of control over your CORS settings, https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch
fetch('https://rickandmortyapi.com/graphql', {
method: 'POST',
mode: 'cors',
headers: { "content-type": "application/json" },
body: JSON.stringify({
query: `{
character(id: 1) {
name
}
}`
})
})
This request work with fetch for me, uppon testing, if the content-type was not set to application/json the server failed with error 500 instead of showing a 400 bad request
Edit again, it works with axios too, are you sure you get a CORS error ?

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.

.. from origin .. has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status

I'm fairly new to making API requests. I'm am trying to set up an incoming slack webhook using a simple axios post request from my React project, however I keep receiving the CORS policy error. The request works perfectly in insomnia.
I'm using ngrok to expose my web server running on my local machine to the internet (I assumed this would correct the issue.) So I'm making the request from https://...ngrok.io, however I'm still receiving 'Status Code: 400' in my network tab along with the error above.
axios({
method: "post",
url:
"https://hooks.slack.com/services/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",
headers: { "Content-type": "application/json" },
data: { text: "Hello, World!" },
}).then(
(response) => {
console.log(response);
},
(error) => {
console.log(error);
}
);
};
There are similar errors on stackoverflow, but none fix my error. I'd really like to understand why this is happening so any advice would be appreciated.
Fixed it, for those having the same issue:
What worked for me is setting Content-Type header to application/x-www-form-urlencoded. found it in this thread: https://github.com/axios/axios/issues/475 It appears that this triggers "simple request" and therefore avoids triggering CORS preflight. https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS#Simple_requests

no access control origin API axios

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

Having issues getting refresh_token in browser. Can't read XML Response

I’m mainly a front end guy, and I’m having some issues getting data back from an api call. I think I just don’t understand something properly, so it’s proving to be massively frustrating. I wonder if anyone can offer some input.
I make the call like this:
var config = {
headers: {
'Access-Control-Allow-Origin': '*',
'Content-Type': 'application/xml',
},
proxy: {
host: '127.0.0.1',
port: 3000
}
};
axios
.post(
`https://login.salesforce.com/services/oauth2/token?grant_type=authorization_code&redirect_uri=http://localhost:3000/callback/&client_id=CLIENT_ID&client_secret=CLIENT_SECRET&code=${authCode}`,
config
)
.then(res => {
console.log(`statusCode: ${res.statusCode}`);
console.log('Result:', res);
})
.catch(error => {
console.error('Error:', error);
});
Then the response I get is this:
Access to XMLHttpRequest at 'https://login.salesforce.com/services/oauth2/token?
grant_type=authorization_code&redirect_uri=http://localhost:3000/callback/&client_id=CLINET_ID&client_secret=CLIENT_SECRET&code=AUTH_CODE'
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.
and this:
POST https://login.salesforce.com/services/oauth2/token?grant_type=authorization_code&redirect_uri=https://localhost:3000/callback/&client_id=3[ID]&client_secret=[SECRET]&code=[CODE] 400 (Bad Request)
But if I put this link in my browser: https://login.salesforce.com/services/oauth2/token?grant_type=authorization_code&redirect_uri=http://localhost:3000/callback/&client_id=CLINET_ID&client_secret=CLIENT_SECRET&code=AUTH_CODE I can see it’s an XML file with all the info I need. So why can’t I just get that info in my response?
This is what I see when I paste the link in my browser:
<OAuth>
<access_token>
{Token}
</access_token>
<refresh_token>
{Token}
</refresh_token>
<signature>{Signature}</signature>
<scope>refresh_token api full</scope>
<id_token>
{Token}
</id_token>
<instance_url>https://um5.salesforce.com</instance_url>
<id>
{ID}</id>
<token_type>Bearer</token_type>
<issued_at>1558167449074</issued_at>
</OAuth>
I've obviously taken out the actual tokens. This is the info I need.
Please can someone assist me in actually accessing that XML info on the front end? Id I do the request on Postman, I get exactly what I need.
I fixed it by using this code on a Node server and seemed to be getting the response I needed:
var request = require('request');
var options = {
url: `https://login.salesforce.com/services/oauth2/token?grant_type=authorization_code&redirect_uri=http://localhost:3000/callback/&client_id=CLIENT_ID.&client_secret=CLIENT_SECRET&code=${token}`
};
function callback(error, response, body) {
if (!error) {
console.log('Body: ', body);
} else {
console.log('Error: ', error);
}
}
I hope this helps someone. Salesforce documentation is very disjointed and complicated.

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