首页 > 解决方案 > WorldPay AJAX 请求的 CORS/预检错误

问题描述

我正在接受其他人使用自定义模板的工作,但出现以下错误:

Failed to load https://api.worldpay.com/v1/orders: Response to the preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://xxx.xxx.xxx.xxx' is therefore not allowed access.

下面是发送 AJAX 请求的代码:

$.ajax({
            type: "POST",
            url: "https://api.worldpay.com/v1/orders",
            dataType: 'json',
            async: false,
            headers: {
              'Access-Control-Allow-Origin': '*',
              "Authorization": worldPayServiceKey
            },
            data: JSON.stringify(options),
            success: function (response){
              if (response.paymentStatus == 'SUCCESS') {
                current_booking.payment = obj.response;
              } else {
                alert("Sorry, there was a problem with your payment. We will send you an invoice instead.");
              }

              makeBooking();
            }
          });

我之前在 CORS 上遇到过类似的问题,但我之前没有看到预检错误。有人可以帮忙吗?

标签: javascriptjqueryajax

解决方案


Access-Control-Allow-Origin从请求标头中删除标头。那是服务器端的标头。

然后将 Content-Type 添加为,

application/x-www-form-urlencodedmultipart/form-data或者text/plain取决于您随请求发送的内容。例如,

headers: {
              "Content-Type": "application/x-www-form-urlencoded",
              "Authorization": worldPayServiceKey
            },

Content-Type 标头的唯一允许值是:

> - application/x-www-form-urlencoded
> - multipart/form-data 
> - text/plain

有关更多信息,请阅读MDN 文档

希望能帮助到你。祝你好运。


推荐阅读