尝试通过 paypal api 创建付款时如何修复响应:{type: "cors"}

Isr*_*tés 12 javascript paypal fetch cors reactjs

我正在测试 fetch API 以使用 PayPal plus 创建付款

\n\n

我的第一个获取函数工作正常,我执行 Oauth 来获取不记名令牌,这样我就可以获得 access_token 来进行付款

\n\n
callPaypal = async () => {\n    try {\n      const details = {\n        grant_type: "client_credentials"\n      };\n      var formBody = [];\n      for (var property in details) {\n        var encodedKey = encodeURIComponent(property);\n        var encodedValue = encodeURIComponent(details[property]);\n        formBody.push(encodedKey + "=" + encodedValue);\n      }\n      formBody = formBody.join("&");\n      var request = {\n        method: "POST",\n        headers: {\n          "Content-Type": "application/x-www-form-urlencoded; charset=UTF-8",\n          Authorization:\n            "Basic <secrets>",\n          "cache-control": "no-cache"\n        },\n        body: formBody\n      };\n      const res = await fetch("https://api.sandbox.paypal.com/v1/oauth2/token", request);\n      const data = await res.json();\n      console.log(data);\n      const access_token = data.access_token;\n      this.makePaymentPaypal(access_token);\n    } catch (error) {}\n  };\n
Run Code Online (Sandbox Code Playgroud)\n\n
makePaymentPaypal = async (access_token) => {\n    try {\n      var request = {\n        method: "POST",\n        headers: {\n          "Access-Control-Allow-Origin": "*",\n          "Content-Type": "application/json",\n          Authorization: `Bearer ${access_token}`,\n          "cache-control": "no-cache"\n        },\n        body: JSON.stringify({\n          intent: "sale",\n          application_context: {\n            shipping_preference: "SET_PROVIDED_ADDRESS"\n          },\n          payer: {\n            payment_method: "paypal",\n            payer_info: {\n              billing_address: {\n                line1: "Mariano Escobedo 476 piso 14",\n                line2: "Anzures, Miguel Hidalgo",\n                city: "Mexico DF",\n                country_code: "MX",\n                postal_code: "11590",\n                state: "DF"\n              }\n            }\n          },\n          transactions: [\n            {\n              amount: {\n                currency: "MXN",\n                total: "522.00",\n                details: {\n                  subtotal: "522.00"\n                }\n              },\n              description: "Pedido en Envia Flores",\n              payment_options: {\n                allowed_payment_method: "IMMEDIATE_PAY"\n              },\n              invoice_number: "94234212",\n              item_list: {\n                items: [\n                  {\n                    name: "Arreglo de flores",\n                    description: "Amigo secreto",\n                    quantity: "1",\n                    price: "290.00",\n                    sku: "sku01",\n                    currency: "MXN"\n                  },\n                  {\n                    name: "Ilumina su dia",\n                    description: "Ilumina su dia",\n                    quantity: "1",\n                    price: "290.00",\n                    sku: "sku02",\n                    currency: "MXN"\n                  },\n                  {\n                    name: "Descuento",\n                    description: "Descuento",\n                    quantity: "1",\n                    price: "-58.00",\n                    sku: "skiu12",\n                    currency: "MXN"\n                  }\n                ],\n                shipping_address: {\n                  recipient_name: "Costumer Costumer",\n                  line1: "Mariano Escobedo 476 piso 14",\n                  line2: "Anzures, Miguel Hidalgo",\n                  city: "Mexico DF",\n                  country_code: "MX",\n                  postal_code: "11590",\n                  state: "DF",\n                  phone: "54545454"\n                }\n              }\n            }\n          ],\n          redirect_urls: {\n            cancel_url: "https://www.example.com",\n            return_url: "https://www.example.com"\n          }\n        })\n      };\n      const res = await fetch("https://api.sandbox.paypal.com/v1/payments/payment", request, {\n        mode: "no-cors"\n      });\n      const data = await res.json();\n      console.log(data)\n    } catch (error) {}\n  };\n
Run Code Online (Sandbox Code Playgroud)\n\n

编辑问题,因为我已经解决了它,下面的代码丢失了,我需要将响应转换为 json。

\n\n
      const data = await res.json();\n      console.log(data)\n
Run Code Online (Sandbox Code Playgroud)\n\n

添加此新代码之前的旧错误消息是:

\n\n
Response\xc2\xa0{type: "cors", url: "https://api.sandbox.paypal.com/v1/payments/payment", redirected: false, status: 201, ok: true,\xc2\xa0\xe2\x80\xa6}\n
Run Code Online (Sandbox Code Playgroud)\n

Isr*_*tés 20

我终于找到了解决方案,代码没问题,缺少的是响应需要用 json() 进行转换,如下所示:

  const res = await fetch("https://api.sandbox.paypal.com/v1/payments/payment", request);
  var data = await res.json();
  console.log(data);
Run Code Online (Sandbox Code Playgroud)

将 res.json 添加到响应后,我可以正确读取它。

  • `var data = wait res.json();` 如何帮助删除 cors ?我面临同样的问题 (4认同)
  • @NoobCoder 如果你仔细观察响应,它会说: ```type: "cors"``` 但状态是 ```status: 201``` 这是我们的请求成功的第一个线索,问题出在其他地方这个具体案例。所以这不是 CORS 问题,只是响应的类型是 CORS(跨源资源共享),当根本问题是服务器缺少 CORS 标头时,错误消息将类似于:```` cors 错误 由于 cors 政策,请求已被阻止``` (2认同)