邮递员工作,但不响应redux操作(axios.post请求)

时间:2020-06-02 10:02:20

标签: node.js reactjs axios google-cloud-functions

确实很奇怪。 我正在使用Cloud Functions构建API。基本上,Cloud 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!")
        }
    }
}

但是在邮递员成功的过程中,我得到了

[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");
    }
  });
});

1 个答案:

答案 0 :(得分:0)

请尝试使用then / catch捕获错误或处理承诺拒绝。

您可以使用以下代码:

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);
    }
}

请告诉我它是否有效。