【问题标题】:Cannot read POST response body from external api in firebase cloud functions无法从 Firebase 云函数中的外部 api 读取 POST 响应正文
【发布时间】:2020-07-30 00:01:37
【问题描述】:

我有一个云函数,它向 LinkedIn API 发出 http POST 请求以检索访问令牌。问题是我无法读取响应的body,它始终是undefined

这是代码

exports.linkedinToken = functions.https.onRequest((req, res) => {
    let url = "https://linkedin.com/oauth/v2/accessToken?...REQUIRED_PARAMS...";

    request.post(url, {json: true}, (err, response, body) => {
      if (!!err) { // this is never happening
        console.log(err);
        throw err;
      } else {
        console.log(response.body); // this is always undefined
        console.log(body); // this is always undefined
      }
});

如果我用 Postman 或 curl 尝试相同的请求,它会完美运行,但我无法真正理解为什么。

在此请求之前,我向linkedin API 发出了另一个GET 请求,它工作正常。可能 POST 请求有问题。

【问题讨论】:

    标签: javascript node.js firebase google-cloud-functions linkedin-api


    【解决方案1】:

    我认为您缺少标题。

    var request = require('request');
    request.post({
      headers: {
        'content-type' : 'application/x-www-form-urlencoded',
        'cache-control' : 'no-cache'
      },
      url: url
    }, function(error, response, body){
      console.log(body);
    });
    

    【讨论】:

    • 我使用 axios 而不是 request 解决了它。也许原因是 axios 包含了请求中缺少的这些标头。我会尝试,然后我会检查这个答案是否正确。谢谢
    猜你喜欢
    • 1970-01-01
    • 2017-10-22
    • 2019-04-08
    • 2022-11-13
    • 2014-04-21
    • 2019-04-19
    • 2021-08-12
    • 2021-11-17
    • 1970-01-01
    相关资源
    最近更新 更多