Why My Request turn post to option with Axios? - reactjs

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

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.

CORS errors on Axios Graphql query

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 ?

Axios get request getting cors issue

i'm trying to get some data from some endpoint.
I can't share the url of endpoint here but problem with cors.
when i'm using postman everything is ok.
But when make get request from my react app via axios i'm getting this error:
Refused to set unsafe header "origin"
Access to XMLHttpRequest at 'http://some.com/products.json' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
here is my request:
const baseUrl = "http://some.com/products.json"
const axiosConfig = {
withCredentials: true,
headers: {
Accept: "application/json",
"Content-Type": "application/json",
}
};
axios
.get(baseUrl, axiosConfig)
.then(response => {
console.log(response);
})
.catch(error => {
console.log(error)
});
i tried many things but i can't figure out with this.
You need to enable CORS in your server, if you have access to your server add the following line to your server.
'Access-Control-Allow-Origin', '*'
for nodejs server
app.use(function(req, res, next) {
res.setHeader('Access-Control-Allow-Origin', '*');
}
for local development you can bypass cors by disabling chrome security, open chrome using --disable-web-security flag, close all instances of Chrome
# Open chrome and disable security
open -a Google\ Chrome --args --disable-web-security --user-data-dir="/Users/junius/chrome/"
# Open Microsoft Edge
open -a Microsoft\ Edge --args --disable-web-security --user-data-dir="/Users/junius/chrome/"
No 'Access-Control-Allow-Origin' header is present on the requested resource
As your error states, perhaps the problem will be solved if you specify the header like this.
headers: {
'Access-Control-Allow-Origin': '*',
}
Similar issue was reported on github.
Getting 'Cross-Origin Request Blocked' on a GET request #853
https://github.com/axios/axios/issues/853

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

Api call cause error 'Access-Control-Allow-Origin' header is present on the requested resource

I am trying to call an api but it is giving me following error :
Access to fetch at 'https://someapi.url/profile?FullName=sadaf&DateFrom=2000-01-01' 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.
I am using react and the code is :
try {
let url = `https://someapi.url/profile?FullName=sadaf&DateFrom=2000-01-01`;
let response = await fetch(url,{
mode: 'cors', // no-cors,
credentials: 'include',
headers: {
'Content-Type': 'application/json',
"Accept": 'application/json',
'Origin' : 'http://localhost:3000'
//'Content-Type': 'text/xml'
// 'Content-Type': 'application/x-www-form-urlencoded',
},
});
this.setState(() => {
return {
searchResults : response
}
})
} catch (error) {
console.error(error);
}
please guide what to do
The error is due to CORS, there is nothing wrong with the front-end code.
Cross-Origin Resource Sharing (CORS) is a mechanism that uses
additional HTTP headers to tell browsers to give a web application
running at one origin, access to selected resources from a different
origin.
To fix this issue, the server should set the CORS headers,
See here on how to enable CORS for your server
If your server is running express you need to set cors like this,
app.use(function(req, res, next) {
// update to match the domain you will make the request from
res.header("Access-Control-Allow-Origin", "YOUR-DOMAIN.TLD");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});
or use the cors middleware for express

Resources