Warm tip: This article is reproduced from serverfault.com, please click

Node.JS Firebase Cloud Function-HTTP请求

(Node.JS Firebase Cloud Function - HTTP Request)

发布于 2020-11-30 15:10:54

我正在编写一个Firebase云函数,以便在HTTP触发时连接到外部数据库。

此功能将执行以下操作:

  1. 用户提交帐号和邮政编码
  2. 云功能被触发
  3. 帐号被附加到请求中的URL,并且外部数据库返回帐号和邮政编码。

我需要将响应主体返回给客户端。

var functions = require('firebase-functions');
var request = require('request');

exports.account_verification = functions.https.onCall((data, context) => {
    console.log("Data: " + data.text);
    console.log("Context: " + context)

    var options = {
        'method': 'GET',
        'url': '**REDACTED**' + JSON.parse(data.text).customerno,
        'headers': {
        }
    };


     request(options, function (error, response) {
        if (error) throw new Error(error);
        console.log("RESPONSE BODY: ", JSON.parse(response.body).firebase_accounts);
        console.log("Data Submitted: ", data.text);
        console.log("Account Submitted: ", JSON.parse(data.text).customerno);
        console.log("Zip Submitted: ", JSON.parse(data.text).zipcode);

        //data returned from external database
        //Example: firebase_accounts:[{"customerno" : "Example Customer", "zipcode" : "Example Zip Code"}]


        var response_returned = JSON.parse(response.body).firebase_accounts;
         console.log("Data Returned -- Parsed: ", response_returned);
        //Example: [{"customerno" : "Example Customer", "zipcode": "Example Zip Code"}]

 //Response Body available here but will not return to client

    });

//Return to client will work here but cannot access response data

});
Questioner
Arcade336
Viewed
11
Frank van Puffelen 2020-12-01 00:19:05

由于你正在执行异步请求,因此需要确保Cloud Functions等待该结果。有时这被称为冒泡结果。

使用诺言最简单,但是由于使用的是request模块,因此模块不可用。相反,你可以创建自己的承诺,如下所示:

var functions = require('firebase-functions');
var request = require('request');

exports.account_verification = functions.https.onCall((data, context) => {
    var options = {
        'method': 'GET',
        'url': '**REDACTED**' + JSON.parse(data.text).customerno,
        'headers': {
        }
    };

    return new Promise(function(resolve, reject) {
      request(options, function (error, response) {
        if (error) reject(error);

        var response_returned = JSON.parse(response.body).firebase_accounts;

        resolve(response_returned);
      });
    })
});