在接收值并计算值的 Firebase 函数中构建 API 端点

Building API end point in Firebase Functions that receives values and calculates them

我正在尝试构建一个 function/endpoint 来接收一些值,计算它们,然后 return 一个 pass/fail 和一条消息,希望它能像这样工作:

export const processLoanRequest = functions.https.onRequest(async (request, response) => {
  // Receive values
  // determine if values they pass a criteria
  // returns true (pass) or false (fail), as well as a message that says why
  })

我尝试了一些方法,看看是否可以立即使用它,但我认为我什至没有接近这个结果:

export const processLoanRequest = functions.https.onRequest((request, response) => {
  console.log({ request, response });
  const obj = {
    name: 'the object',
    param: 'object param',
  };
  response.json(obj);
});

我在我的 React 应用程序中编写的用于 post 请求的函数是从 MDN Web Docs -- Using Fetch 复制的,看起来像:

// Example POST method implementation:
  async function postData(url = '', data = {}) {
    // Default options are marked with *
    const response = await fetch(url, {
      method: 'POST',
      mode: 'no-cors',
      cache: 'no-cache',
      credentials: 'same-origin',
      headers: {
        'Content-Type': 'application/json',
      },
      redirect: 'follow',
      referrerPolicy: 'no-referrer',
      body: JSON.stringify(data),
    });
    return response.json();
  }

  const handleSubmit = values => {
    console.log(values);
    // postLoanInfo(values).then(data => console.log(data));
    postData(
      'https://us-central1-autoloan-24e0d.cloudfunctions.net/processLoanRequest',
      { ...values }
    )
      .then(data => {
        console.log(data); // JSON data parsed by `data.json()` call
      })
      .catch(err => console.log(err));
  };

对于这些,我总是以一条错误消息告终:

SyntaxError: Unexpected end of input
    at LoanForm.js:35
    at s (runtime.js:63)
    at Generator._invoke (runtime.js:293)
    at Generator.next (runtime.js:118)
    at r (asyncToGenerator.js:3)
    at u (asyncToGenerator.js:25)

来自 catch(err...),第 35 行是 return response.json(); in postData(..)。当请求被 posted 时 body 会发生什么?它是如何在端点接收的,我如何从那里访问它?

values object 看起来像:

{purchasePrice: 12000, autoMake: "kia", autoModel: "soul", yearlyIncome: 50000, creditScore: 680}

谢谢!

更新: 事实证明,我必须在下面实施 Rafael 的解决方案以及 response.set('Access-Control-Allow-Headers', 'Content-Type'); 才能使其正常工作。我不是很有经验,所以我没有想到在开发工具中的网络选项卡下查看,它给出了必须更改的内容。

更新2: response.set('Access-Control-Allow-Headers', 'Content-Type'); 仅在您 post 请求具有 headers 时才需要(即具有包含值的 body)。上面的例子没有必要,因为我没有 posting 任何东西,我只是在 return.

中得到 obj 的值

作为社区 Wiki 回答,因为这是基于@RobertNubel 的评论。

您收到的错误意味着响应正文无效JSON,这很可能是由后台的其他错误引起的。您可以在 React 站点上打开浏览器的网络检查器来监视 API 调用,因为它是为了获取有关正在发生的事情的更多信息。

正如您在此 上看到的,此问题很可能是由于您在云功能的响应中缺少 CORS 配置造成的,要解决此问题,您只需添加您的函数的几行额外行如下:

export const processLoanRequest = functions.https.onRequest((request, response) => {
  console.log({ request, response });
  const obj = {
    name: 'the object',
    param: 'object param',
  };
  response.set('Access-Control-Allow-Origin', "*")
  response.set('Access-Control-Allow-Methods', 'GET, POST')
  response.set('Access-Control-Allow-Headers', 'Content-Type')
  response.json(obj);
});