14

我一直在尝试新的 firebase 可调用云功能,firebase functions:shell但我不断收到以下错误

请求的 Content-Type 不正确。

从函数收到的响应:400,{"error":{"status":"INVALID_ARGUMENT","message":"Bad Request"}}

这是我尝试在 shell 上调用此函数的方法

myFunc.post(数据对象)

我也试过这个

myFunc.post().form(dataObject)

但后来我得到错误的编码(形式)错误。dataObject是有效的 JSON。

更新:

我认为我需要用于这些功能firebase serve的本地仿真。callable https数据需要像这样在 post 请求中传递(注意它是如何嵌套在data参数中的)

{
 "data":{
    "applicantId": "XycWNYxqGOhL94ocBl9eWQ6wxHn2",
    "openingId": "-L8kYvb_jza8bPNVENRN"
 }
}

我仍然想不通的是如何在通过 REST 客户端调用该函数时传递虚拟身份验证信息

4

4 回答 4

18

我设法让它从函数外壳中运行它:

myFunc.post('').json({"message": "Hello!"})

于 2018-04-06T11:49:37.403 回答
3

据我所知,该函数的第二个参数包含所有附加数据。传递一个包含headers地图的对象,您应该能够指定您想要的任何内容。

myFunc.post("", { headers: { "authorization": "Bearer ..." } });

如果您使用 Express 来处理路由,那么它看起来像:

myApp.post("/my-endpoint", { headers: { "authorization": "Bearer ..." } });
于 2018-08-14T13:06:31.550 回答
2

CLI 的正确语法已更改为myFunc({"message": "Hello!"})

于 2020-05-27T20:03:12.997 回答
2

如果你看一下源代码,你会发现它只是一个普通的 https post 函数,它带有一个包含 json web 令牌的身份验证头,我建议使用单元测试 api 用于 https 函数并模拟头方法从测试用户以及请求正文返回令牌

[更新]示例

const firebase = require("firebase");
var config = {
  your config
};
firebase.initializeApp(config);
const test = require("firebase-functions-test")(
  {
    your config
  },
  "your access token"
);
const admin = require("firebase-admin");
const chai = require("chai");
const sinon = require("sinon");

const email = "test@test.test";
const password = "password";
let myFunctions = require("your function file");
firebase
  .auth()
  .signInWithEmailAndPassword(email, password)
  .then(user => user.getIdToken())
  .then(token => {
    const req = {
      body: { data: { your:"data"} },
      method: "POST",
      contentType: "application/json",
      header: name =>
        name === "Authorization"
          ? `Bearer ${token}`
          : name === "Content-Type" ? "application/json" : null,
      headers: { origin: "" }
    };
    const res = {
      status: status => {
        console.log("Status: ", status);
        return {
          send: result => {
            console.log("result", result);
          }
        };
      },
      getHeader: () => {},
      setHeader: () => {}
    };
    myFunctions.yourFunction(req, res);
  })
  .catch(console.error);
于 2018-04-10T18:16:41.130 回答