CORS issue in Axios - reactjs

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.

Related

Unable to fetch data from AWS api gateway with python lambda function to react js frontend using axios

I am trying to access data from AWS api gateway. Which works fine without an api-key but after the api-key is enabled the data is not retrived from the server while it works alright with postman testing.
The error in the browser is shows as follows ->
Access to XMLHttpRequest at 'https://bvoj5hykj0.execute-api.us-east-1.amazonaws.com/test/testresource' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.
The server-side lambda function python code is given as follows
import json
def lambda_handler(event,context):
return {
'statusCode': 200,
'headers':{
"Access-Control-Allow-Origin": "*",
"Content-Type" : "application/json",
"Access-Control-Allow-Headers" : "Content-Type,X-Amz-Date,Authorization,X-Api-Key,X-Amz-Security-Token,x-api-key",
"Access-Control-Allow-Methods" : "GET"
"Content-Type" : "application/json"
},
'body': json.dumps("changes saved")
}
The react axios code to retrive the data using api-key is as follows ->
async function testAct(){
// The below code block is also been tried and returns same response
// axios.defaults.headers.common = {
// "x-api-key": "xxxxxxxxxxxxxxxxxxxxx"
// }
// const headers = {
// "Content-Type": "application/json",
// "Authorization": "xxxxxxxxx-here-is-my-api-keyxxxxx"
// };
await axios.get("here is aws-api-url-hidden",{
headers: {
"x-api-key": "xxxxxxxxx-here-is-my-api-keyxxxxx"
}
})
.then((response) => {
console.log(response);
setTestRes(response.data);})
.catch((error) => { console.log(error);});
}
The API key and API url is right [ I have checked several times ]
The postman response is alright as below ->
without api-key->
with api-key
I was trying to get the data with aws api-key in reactjs front end. The data comes just fine with postman testing but fails inside react js.
Depending on the API Gateway to Lambda integration configuration, you will also need to enable CORS for API Gateway. This will handle the preflight OPTIONS request as noted by a previous commenter. The browser will perform the OPTIONS check, but Postman (to my knowledge) will not.
A few resources to help you configure API Gateway:
https://docs.aws.amazon.com/apigateway/latest/developerguide/how-to-cors.html
https://aws.amazon.com/blogs/compute/configuring-cors-on-amazon-api-gateway-apis/

Yes, another CORS query. I feel like I have done everything listed but still no beans

I hope you are OK given the current World we all live in. Please can you help with an AWS API Gateway CORS issue. Here is what I have done and yet I still get a
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://XXXXX.execute-api.eu-west-1.amazonaws.com/live/record?id=8. (Reason: CORS request did not succeed).
Response. I am passing an AWS API request through to a Lambda function shown below.
return {
"statusCode": 200,
"body": JSON.stringify({
record: values[0],
prev: values[1],
next: values[2]
}),
"headers": {
"Content-Type": "application/json",
"Access-Control-Allow-Origin" : "*",
"Access-Control-Allow-Headers": "Content-Type",
"Access-Control-Allow-Methods": "OPTIONS,GET",
"Access-Contol-Allow-Credentials": true
}
}
Within the proxy response I have the following headers within the OPTIONS method
And my Axios request within my create-react-app is thus...
useEffect(() => {
axios.get(`http://XXXXX.execute-api.eu-west-1.amazonaws.com/live/record?id=${id}`,{
crossdomain: true
}).then((response) => {
console.log(response)
setRecord(response.data.record)
setNext(response.data.next)
setPrev(response.data.prev)
setMarker([response.data.record.y, response.data.record.x])
})
},[id])
Any ideas?!
OK - solved. Not sure which of the moving parts was needed. Originally I had https but changed it to http as a part of the testing. Changed it back, and it works. I would be interested to know if something is not needed here.

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.

Can't set customized header value with fetch

I want to send API KEY in the headers of my request. I use fetch method like this (I use react and its in shopify module) :
fetch("https://shopify.mysite.fr/shopify/articles/1", {
method: "GET",
mode: "cors",
headers: {
"Content-Type": "application/json",
"x-auth-token":"$2y$13$Kf0P46IM19qsdqk78SuB6CeuFfnonjsdfsdgsdhYvlSsf9uttNOgdjAQnZCz6y"
}
})
.then(res => res.json())
.then(data => {
this.setState({ article: data });
console.log(data);
})
.catch(console.log);
The problem is "x-auth-token" appeared in "access-control-request-headers" field. I just have the name but not the value (the key) and my API respond 401 ...
request headers
What should I do to obtain x-auth-token in the api?
This is the standard behaviour of the CORS enabled requests.
Before an actual call is made (GET with x-auth-token header) the browser is performing CORS preflight. This usually takes a form of additional OPTIONS request with your non-standard headers being sent in access-control-request-headers header, so that during an actual call server would know that it is safe to accept this non-standard header. Your 401 probably means that your API is not configured to accept cross origin calls or that it doesn't now your domain name and therefore prevents you from accessing it.

I can't perform a request from ReactJS. The header can not be written correctly

axios.get('http://localhost:8080/omp/patients', { headers: {authorization: 'Bearer ' + token}})
.then( response => {
this.state = response.data;
}
).catch(ex=> {
alert("You are not registered");
//console.log(e)
});
In network I have the field: "Access-Control-Request-Headers: authorization" but no field "authorization: token"
You will need to set the Authorization header correctly, as in the comment above.
For your reply about CORS Policy:
You will need to learn about CORS, but essentially Chrome and other browsers halt network requests if they do not have proper CORS headers set upon response. A preflight is an initial request that is sent to the same URL to learn whether the URL will support CORS, before sending the actual request. It looks like the server doesn't understand CORS preflights or isn't configured properly.
You have a couple options:
If you have access to the server configuration or code (such as a Laravel or NodeJS server), install a CORS plugin.
If you are the only user using this, you can install CORS browser extensions for Chrome or Firefox or whatever.
Change your code to this:
axios.get('http://localhost:8080/omp/patients', { headers: { "Authorization": 'Bearer ' + token}})
.then( response => {
this.state = response.data;
}
).catch(ex=> {
alert("You are not registered");
//console.log(e)
});
Also in you app.js/index.js where ever you are running your server import/require cors module and do like this:
let cors = require('cors');
app.use(cors());
Hope this helps!

Resources