【问题标题】:Can't get body response with Node from RESTFUL API无法使用来自 RESTFUL API 的 Node 获得正文响应
【发布时间】:2020-09-06 01:56:36
【问题描述】:

我正在尝试使用 Node.js 从 RESTFUL API 获取正文响应,它是发送 GET 请求的“请求”库。代码如下:

const request = require('request');

const url = 'https://myurl.com';

const headers = {
    'x-functions-key': 'mysecretkey'
};
request.get(`${url}${headers}`, (err, response, body) =>{
    if (err){
        console.log(err)
    }
    console.log(body)
})

但是当我运行“node myfile”时,我没有得到正文的响应,控制台返回是空白的。我想我错过了一些东西。我已经用 Postman 测试了 URL 和密钥,它工作正常,JSON 响应出现在那里。 观察:我是 Node 新手,尝试过本教程:https://www.twilio.com/blog/2017/08/http-requests-in-node-js.html。出于安全原因,此处的“url”和“key”被屏蔽了。任何帮助对我来说都很好,我很感激。

【问题讨论】:

  • 你在回复中得到了什么?

标签: javascript node.js api rest request


【解决方案1】:

问题是您不能只将标题放在模板字符串中。您需要使用选项对象指定它们。

request.get({ url: url, headers: headers }, (err, response, body) => { ... });

或者,使用 ES6 简写:

request.get({ url, headers }, (err, response, body) => { ... });

【讨论】:

    【解决方案2】:

    问题是在request.get 行你有你的 URL 和标题模板

    `${url}${headers}`
    

    Here's the documentation regarding custom headers

    所以解决方案是创建一个像这样的选项变量:

    const options = {
      url: 'https://myurl.com',
      headers: {
        'x-functions-key': 'mysecretkey'
      }
    };
    

    然后将其传递给请求

    request.get(options, (err, response, body) =>{
        if (err){
            console.log(err)
        }
        console.log(body)
    })
    

    希望对你有帮助

    【讨论】:

    • 嘿,我很高兴它有帮助。如果您将我的回复标记为有用,我将不胜感激,谢谢
    猜你喜欢
    • 2018-12-04
    • 2019-10-03
    • 1970-01-01
    • 2015-10-23
    • 1970-01-01
    • 1970-01-01
    • 2020-08-25
    • 2022-11-23
    相关资源
    最近更新 更多