【发布时间】:2021-07-14 08:31:47
【问题描述】:
所以我一直在遇到这个 CORS 错误和 401,并尝试了 chrome 插件来允许没有运气的 cors。以下是我通过插件禁用 cors 后遇到的错误:
Access to fetch at 'https://api.playground.klarna.com/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
在启用 CORS Chrome 扩展程序之前,我收到一条 Allow-Access-Control-Origin is not set on the first error message。除了在网络选项卡中,我得到一个 401 Preflight,它表示未经授权,但我正在使用正确的凭据设置 Authorization 标头,所以不确定这里发生了什么。我正在使用 codeigniter php 框架。
我正在使用基本身份验证:
var auth = 'Basic ' + btoa(username:password);
代码如下:
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.com/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);
});
我已经尝试将模式设置为 no-cors 并收到相同的响应。我使用邮递员发布了具有相同数据的请求,并且在邮递员中收到了响应。不确定我是否遗漏或忽略了某些东西,所以一个新的视角会有所帮助。有谁知道如何继续解决这个问题?我想避免必须将此代码部署到实时域并能够在 localhost 上测试响应,但不确定是否可以使用 cors。
【问题讨论】:
-
auth的作曲怎么样? -
@ChrisG var auth = 'Basic' + btoa(username:password);
-
那是您使用的确切代码吗...?
-
我也面临同样的问题,401 或 CROS 策略与 Allow-Access-Control-Origin 的错误。
-
基于this 我的猜测是Klarna 不支持从浏览器端JavaScript 访问API。这是有道理的,因为您会以这种方式向网站访问者公开凭据。
标签: javascript cors fetch