簡體   English   中英

Postman 工作但不反應 redux 操作(axios.post 請求)

[英]Postman works but not react redux action (axios.post request)

真正奇怪的事情正在發生。 我正在使用 Cloud Functions 構建一個 API。 基本上,雲 Function 向服務器發出請求並檢索令牌。

這是代碼

exports.Klarna = functions.https.onRequest((req, res) => {
  // const app = express();
  // app.use(cors({ origin: true }));
  res.set('Access-Control-Allow-Origin', '*');
  const url = "https://someLink.com";
  const creds = req.body;
  const token = `Basic  ${Buffer.from(
    `${"Pxxx"}:${"xxx"}`
  ).toString("base64")}`;

  request(
    "https://somelink.com",
    {
      method: "POST",
      url: url,
      headers: {
        "Content-Type": "application/json",
        "Access-Control-Allow-Origin": "*",
        Authorization: token,
      },
      Authorization: token,
      body: creds,
      json: true,
    },
    function (error, response, body) {
      if (!error && response.statusCode === 200) {
        console.log(body);
        res.json(response.body.client_token);
      }
    }
  );
});

然后我使用 redux-thunk 和 axios 從前端(reactJS)調用它:

export function Klarna() {
    return async (dispatch) => {
        try {

            let response = await axios('https://google.cloud.function', {
                method: 'POST',
                redirect: 'follow',
                headers: { 'Content-Type': 'application/json', "Access-Control-Allow-Origin": "*",Authorization: "Basic XXX" },
                body: JSON.stringify({
                    "purchase_country": "SE",
                    "purchase_currency": "SEK",
                    "locale": "sv-SE",
                    "order_amount": 10,
                    "order_tax_amount": 0,
                    "order_lines": [
                        {
                            "type": "physical",
                            "reference": "19-402",
                            "name": "Battery Power Pack",
                            "quantity": 1,
                            "unit_price": 10,
                            "tax_rate": 0,
                            "total_amount": 10,
                            "total_discount_amount": 0,
                            "total_tax_amount": 0
                        }
                    ]
                }), 
                json: true
            })
            console.log(response);
        } finally {
            console.log("yea!")
        }
    }
}

但是在 postman 成功時,我得到了

[Error] Failed to load resource: The request timed out. (Klarna, line 0)
[Error] Unhandled Promise Rejection: Error: timeout of 0ms exceeded
    (anonymous function) (main.chunk.js:7307)
    asyncFunctionResume
    (anonymous function)
    promiseReactionJobWithoutPromise
    promiseReactionJob

有什么建議可以幫助我繼續前進嗎? 在這個錯誤周圍已經有 2 天了,我沒有看到解決它的方法。

更新:

我四處走走,找到了怎么做。 這是代碼:


const functions = require("firebase-functions");

const express = require("express");
var rp = require("request-promise");

const cors = require("cors")({
  origin: true,
  allowedHeaders: [
    "Access-Control-Allow-Origin",
    "Access-Control-Allow-Methods",
    "Content-Type",
    "Origin",
    "X-Requested-With",
    "Accept",
    "Authorization"
  ],
  methods: ["POST", "OPTIONS"],
  credentials: true,
});

const admin = require("firebase-admin");
const serviceAccount = require("./serviceAccountKey.json");
var request = require("request");

admin.initializeApp({
  credential: admin.credential.cert(serviceAccount),
});


exports.Klarnas = functions.https.onRequest((req, res) => {
  // Google Cloud Function res.methods
  res.set("Access-Control-Allow-Headers", "Content-Type");
  res.set("Content-Type", "Application/JSON");
  // CORS-enabled req.methods, res.methods
  return cors(req, res, async () => {
    res.set("Content-Type", "Application/JSON");
    var origin = req.get("Origin");
    var allowedOrigins = [
      "https://yourLink.com",
      "http://localhost:3000",
      "http://localhost:5001/xxx/xxx",
    ];
    if (allowedOrigins.indexOf(origin) > -1) {
      // Origin Allowed!!
      res.set("Access-Control-Allow-Origin", origin);
      if (req.method === "OPTIONS") {
        // Method accepted for next request
        res.set("Access-Control-Allow-Methods", "POST");
        //SEND or end
        return res.status(200).send({});
      } else {
        // After req.method === 'OPTIONS' set ["Access-Control-Allow-Methods": "POST"]
        // req.method === 'POST' with req.body.{name} => res.body.{name}
        // req.method === 'PUT' with req.body.{name}, no res.body.{name}
        const url = "https://someLink.com";
        const creds = req.body;
        const token = `Basic  ${Buffer.from(
          `${"XXXX"}:${"XXX"}`
        ).toString("base64")}`;
        request(
          "https://someLink.com",
          {
            method: "POST",
            url: url,
            headers: {
              "Content-Type": "application/json",
              "Access-Control-Allow-Origin": "*",
              Authorization: token,
            },
            Authorization: token,
            body: creds,
            json: true,
          },
          function (error, response, body) {
            if (!error && response.statusCode === 200) {
              console.log(body);
              res.json(response.body.client_token);
            }
          }
        );
      }
    } else {
      //Origin Bad!!
      //SEND or end
      return res.status(400).send("no access for this origin");
    }
  });
});

請嘗試使用 then/catch 來捕獲錯誤或處理 promise 拒絕。

您可以使用以下代碼:

export function Klarna() {
    return async (dispatch) => {

            let response = await axios('https://[REGION]-[PROJECT-ID].cloudfunctions.net/Klarna', {
                method: 'POST',
                redirect: 'follow',
                headers: { 'Content-Type': 'application/json', "Access-Control-Allow-Origin": "*",Authorization: "Basic [Token]==" },
                body: JSON.stringify({
                    "purchase_country": "SE",
                    "purchase_currency": "SEK",
                    "locale": "sv-SE",
                    "order_amount": 10,
                    "order_tax_amount": 0,
                    "order_lines": [
                        {
                            "type": "physical",
                            "reference": "19-402",
                            "name": "Battery Power Pack",
                            "quantity": 1,
                            "unit_price": 10,
                            "tax_rate": 0,
                            "total_amount": 10,
                            "total_discount_amount": 0,
                            "total_tax_amount": 0
                        }
                    ]
                }), 
                json: true
            }).then(data => console.log(data))
              .catch(err => console.log(err);
    }
}

請讓我知道它是否有效。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM