通过 Axios 向 Firebase 云函数发送 POST 请求

Jea*_*ean 2 javascript rest firebase google-cloud-functions axios

我尝试向 Firebase 函数发送一个简单的请求,但每次都会出现相同的错误......显然,Firebase 函数没有收到我想从 Axios 请求传输的数据。

这是 Firebase 功能:

[...] // Some imports

exports.completeProfile = functions.https.onRequest((req, res) => {

  // Debug
  console.log(req); 
  console.log(req.body);
  console.log(req.method);
  console.log("Test: " + userId + ", " + profilePicture + ", " + username);

  // We recover the data
  const userId = req.body.userId; // return "undefined"
  const profilePicture = req.body.profilePicture; // return "undefined"
  const username = req.body.username; // return "undefined"

  // we're checking to see if they've been transferred
  if (!userId || !profilePicture || !username) {
    // At least one of the 3 required data is not completed
    console.error("Error level 1: missing data");
    return res.status(400).send("Error: missing data");
  }

  [...] // (We have all the data, we continue the function)

});
Run Code Online (Sandbox Code Playgroud)

这是我的 Axios 请求:

axios
    .post(
        '<FIREBASE CLOUD FUNCTION URL>',
        {
            userId: '12345667',
            profilePicture: 'https://profilepicture.com/url',
            username: 'test',
        }
    )
    .then(function(response) {
        console.log(response);
    })
    .catch(function(error) {
        console.log(error);
    });
Run Code Online (Sandbox Code Playgroud)

当我运行 Axios 查询时,我总是遇到“网络错误”错误。这是console.log(error); 给出: 在此处输入图片说明

这是服务器日志: 在此处输入图片说明

如何解决问题?谢谢你的帮助。

小智 7

将您的 Firebase 代码更改为此

var cors = require("cors");
completeProfileFn = (req, res) => {
  // Debug
  console.log(req);
  console.log(req.body);
  console.log(req.method);
  console.log("Test: " + userId + ", " + profilePicture + ", " + username);

  // We recover the data
  const userId = req.body.userId; // return "undefined"
  const profilePicture = req.body.profilePicture; // return "undefined"
  const username = req.body.username; // return "undefined"

  // we're checking to see if they've been transferred
  if (!userId || !profilePicture || !username) {
    // At least one of the 3 required data is not completed
    console.error("Error level 1: missing data");
    return res.status(400).send("Error: missing data");
  }

  // (We have all the data, we continue the function)
};

// CORS and Cloud Functions export logic
exports.completeProfile = functions.https.onRequest((req, res) => {
  var corsFn = cors();
  corsFn(req, res, function() {
    completeProfileFn(req, res);
  });
});
Run Code Online (Sandbox Code Playgroud)

这是一个 CORS 问题。