【问题标题】:How do I resolve a cors error on a fetch or 401?如何解决 fetch 或 401 上的 cors 错误?
【发布时间】: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


【解决方案1】:
  • 众所周知,浏览器扩展在处理预检请求方面毫无用处。在这里没有用。
  • No-cors 模式使浏览器静默失败任何需要 CORS 权限的操作,而不是引发异常。在这里没有用。
  • Postman 不是浏览器。它的请求不是通过访问网站来触发的。它没有实施同源策略,也不需要 CORS 的许可。

我收到一个 401 Preflight,表示未经授权,但我正在使用正确的凭据设置 Authorization 标头,因此不确定这里发生了什么。

浏览器正在发出预检请求,请求允许发送带有凭据的 POST 请求。

服务器正在获取预检请求并抱怨它没有凭据。

要么:

  • 更改您发出请求的服务器,以便在您的开发环境中授予您权限。它需要允许没有凭据的 OPTIONS 请求。
  • 使用代理将您的请求中继到服务器

【讨论】:

    【解决方案2】:

    您的后端是 .net 核心网络服务吗?如果是这样,当您在管道中的 UseAuthentication 之后调用 UseCors 时,我已经看到了这个问题。如果你这样做,你将需要一个经过身份验证的令牌来进行预检,这就是为什么你会得到一个抛出异常的 cors 错误。将 UseCors 移到 UseAuthentication 之前,这样 CORS 响应就不必先通过 Authentication 中间件。

    【讨论】:

    • 正如目前所写,您的答案尚不清楚。请edit 添加其他详细信息,以帮助其他人了解这如何解决所提出的问题。你可以找到更多关于如何写好答案的信息in the help center
    猜你喜欢
    • 2020-02-22
    • 2021-09-27
    • 1970-01-01
    • 2018-06-22
    • 2014-04-08
    • 2021-05-28
    • 2019-03-18
    • 2021-11-30
    • 2014-05-04
    相关资源
    最近更新 更多