admin管理员组文章数量:1323323
So I've been experiencing this CORS error and a 401 and have tried chrome plugins to allow for cors with no luck. Here are the errors I'm getting after disabling cors via the plugin:
Access to fetch at '' from origin 'https://localhost' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.
Failed to load resource: net::ERR_FAILED
Error: TypeError: Failed to fetch
Before enabling the CORS Chrome Extension I was receiving a Allow-Access-Control-Origin is not set on the first error message. Along with this in the network tab I'm getting a 401 Preflight which indicates unauthorized but I'm setting the Authorization header with the correct credentials so not sure what's happening here. I'm using the codeigniter php framework.
I'm using Basic auth with:
var auth = 'Basic ' + btoa(username:password);
Here's the code:
let postDataSession = {
"purchase_country" : bookingData.purchase_country,
"purchase_currency" : bookingData.purchase_currency,
"locale" : bookingData.locale,
"order_amount" : bookingData.order_amount,
"order_tax_amount" : 0,
"order_lines" : [{
//"type" : "physical",
"reference" : bookingData.order_lines.reference,
"name" : bookingData.item_name,
"quantity" : 1,
"unit_price" : bookingData.order_amount,
"tax_rate" : 0,
"total_amount" : bookingData.order_amount,
"total_discount_amount": 0,
"total_tax_amount" : 0
}]
};
fetch('', {
method: 'POST',
//mode: 'no-cors',
//Authorization: auth,
headers: {
'Content-Type': 'application/json',
'Authorization': auth,
//'Access-Control-Allow-Credentials' : true,
'Access-Control-Allow-Headers' : 'pm-u, pm-h0, pm-h1, pm-h3, pm-o0, pm-o1, pm-o2, pm-o3, authorization',
'Access-Control-Allow-Methods': 'POST',
'Access-Control-Allow-Origin': 'https://localhost',
'ACCESS-CONTROL-MAX-AGE' : 3600,
'referrer-policy': 'no-referrer-when-downgrade'
},
body: JSON.stringify(postDataSession),
})
.then(function(response) {
//The following method initializes the Klarna Payments JS library
//window.location.href = baseurl + "customer/klarna_checkout_page";
if (!response.ok) {
return response.text().then(result => Promise.reject(new Error(result)));
console.log(response.status);
}
console.log(response.json(), response);
return response.json();
})
// .then(function(session) {
// window.location.href = baseurl + "customer/klarna_checkout_page";
// })
.then(function(result) {
// If `redirectToCheckout` fails due to a browser or network
// error, you should display the localized error message to your
// customer using `error.message`.
if (result.error) {
alert(result.error.message);
}
console.log(result);
})
.catch(function(error) {
console.error('Error:', error);
});
I've tried it the mode set to no-cors and receive the same response. I've used postman to post the request with the same data and in postman a response is received. Not sure if I'm either missing or overlooking something so a fresh perspective would be helpful. Does anyone have any idea how to proceed with resolving this issue? I want to avoid having to deploy this code to the live domain and be able to test the response on localhost, not sure if that's at all possible with cors.
So I've been experiencing this CORS error and a 401 and have tried chrome plugins to allow for cors with no luck. Here are the errors I'm getting after disabling cors via the plugin:
Access to fetch at 'https://api.playground.klarna./payments/v1/sessions' from origin 'https://localhost' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.
Failed to load resource: net::ERR_FAILED
Error: TypeError: Failed to fetch
Before enabling the CORS Chrome Extension I was receiving a Allow-Access-Control-Origin is not set on the first error message. Along with this in the network tab I'm getting a 401 Preflight which indicates unauthorized but I'm setting the Authorization header with the correct credentials so not sure what's happening here. I'm using the codeigniter php framework.
I'm using Basic auth with:
var auth = 'Basic ' + btoa(username:password);
Here's the code:
let postDataSession = {
"purchase_country" : bookingData.purchase_country,
"purchase_currency" : bookingData.purchase_currency,
"locale" : bookingData.locale,
"order_amount" : bookingData.order_amount,
"order_tax_amount" : 0,
"order_lines" : [{
//"type" : "physical",
"reference" : bookingData.order_lines.reference,
"name" : bookingData.item_name,
"quantity" : 1,
"unit_price" : bookingData.order_amount,
"tax_rate" : 0,
"total_amount" : bookingData.order_amount,
"total_discount_amount": 0,
"total_tax_amount" : 0
}]
};
fetch('https://api.playground.klarna./payments/v1/sessions', {
method: 'POST',
//mode: 'no-cors',
//Authorization: auth,
headers: {
'Content-Type': 'application/json',
'Authorization': auth,
//'Access-Control-Allow-Credentials' : true,
'Access-Control-Allow-Headers' : 'pm-u, pm-h0, pm-h1, pm-h3, pm-o0, pm-o1, pm-o2, pm-o3, authorization',
'Access-Control-Allow-Methods': 'POST',
'Access-Control-Allow-Origin': 'https://localhost',
'ACCESS-CONTROL-MAX-AGE' : 3600,
'referrer-policy': 'no-referrer-when-downgrade'
},
body: JSON.stringify(postDataSession),
})
.then(function(response) {
//The following method initializes the Klarna Payments JS library
//window.location.href = baseurl + "customer/klarna_checkout_page";
if (!response.ok) {
return response.text().then(result => Promise.reject(new Error(result)));
console.log(response.status);
}
console.log(response.json(), response);
return response.json();
})
// .then(function(session) {
// window.location.href = baseurl + "customer/klarna_checkout_page";
// })
.then(function(result) {
// If `redirectToCheckout` fails due to a browser or network
// error, you should display the localized error message to your
// customer using `error.message`.
if (result.error) {
alert(result.error.message);
}
console.log(result);
})
.catch(function(error) {
console.error('Error:', error);
});
I've tried it the mode set to no-cors and receive the same response. I've used postman to post the request with the same data and in postman a response is received. Not sure if I'm either missing or overlooking something so a fresh perspective would be helpful. Does anyone have any idea how to proceed with resolving this issue? I want to avoid having to deploy this code to the live domain and be able to test the response on localhost, not sure if that's at all possible with cors.
Share asked Apr 20, 2021 at 6:58 HydraHydra 613 silver badges11 bronze badges 11-
How exactly are you posing
auth
? – user5734311 Commented Apr 20, 2021 at 7:02 - @ChrisG var auth = 'Basic ' + btoa(username:password); – Hydra Commented Apr 20, 2021 at 7:04
- Is that the exact code you're using...? – user5734311 Commented Apr 20, 2021 at 7:06
- I am also facing the same problem, the error of either 401 or CROS policy with Allow-Access-Control-Origin. – Zaid Bin Khalid Commented Apr 20, 2021 at 7:16
- Based on this my guess is that Klarna doesn't support API access from browser-side JavaScript. Which makes sense, given that you'd expose credentials to the website visitor that way. – user5734311 Commented Apr 20, 2021 at 7:27
2 Answers
Reset to default 4Is your backend core web services? If so, I have seen this problem when you call UseCors after UseAuthentication in your pipeline. If you do that, you will need an authenticated token to do the preflight which is why you get a cors error throwing the exception. Move UseCors to before UseAuthentication so that a CORS response does not have to go through the Authentication middleware first.
- Browser extensions are notoriously useless at dealing with preflighted requests. It won't help here.
- No-cors mode makes the browser silently fail anything that requires CORS permission instead of throwing an exception. It won't help here.
- Postman isn't a browser. It's requests aren't triggered by visiting a website. It doesn't implement the Same Origin Policy and doesn't need permission from CORS.
I'm getting a 401 Preflight which indicates unauthorized but I'm setting the Authorization header with the correct credentials so not sure what's happening here.
The browser is making a preflight request asking permission to send a POST request with credentials.
The server is getting the preflight request and plaining that it doesn't have credentials on it.
Either:
- Change the server you are making the request to so it grants you permission in your development environment. It needs to allow OPTIONS requests without credentials on them.
- Use a proxy that relays your requests to the server
本文标签: javascriptHow do I resolve a cors error on a fetch or 401Stack Overflow
版权声明:本文标题:javascript - How do I resolve a cors error on a fetch or 401? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742140439a2422558.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论