简体   繁体   English

无法使用来自 RESTFUL API 的节点获得正文响应

[英]Can't get body response with Node from RESTFUL API

I'm tring to get a body response from a RESTFUL API using Node.js and it's "request" lib to send a GET request.我正在尝试使用 Node.js 从 RESTFUL API 获得正文响应,它是发送 GET 请求的“请求”库。 Here's the code:这是代码:

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)
})

But when I run "node myfile" I get no response from the body, the console return is blank.但是当我运行“node myfile”时,我没有得到正文的响应,控制台返回是空白的。 I think I'm missing something.我想我错过了一些东西。 I've tested the URL and key with Postman and it's working fine, the JSON response appears to me there.我已经用 Postman 测试了 URL 和密钥,它工作正常,JSON 响应在那里出现。 Obs.: I'm new to Node, tried with this tutorial: https://www.twilio.com/blog/2017/08/http-requests-in-node-js.html .观察:我是 Node 新手,尝试使用本教程: https://www.twilio.com/blog/2017/08/http-requests-in-node-js.ZFC35FDC70D5FC69D23EZ88 The "url" and "key are masked here for security reasons. Any help is fine to me, I'm grateful.出于安全原因,“url”和“key”在这里被屏蔽。任何帮助对我来说都很好,我很感激。

The problem is that on request.get line you have your URL and headers templates问题是在request.get行你有你的 URL 和标题模板

`${url}${headers}`

Here's the documentation regarding custom headers这是有关自定义标头的文档

So the solution would be creating an options variable like this:所以解决方案是创建一个像这样的选项变量:

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

And then passing it to request然后将其传递给请求

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

Hope this helps希望这可以帮助

The issue is that you can't just put headers inside the template string.问题是您不能只将标题放在模板字符串中。 You need to specify them with an options object.您需要使用选项 object 指定它们。

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

Or, with ES6 shorthand:或者,使用 ES6 简写:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM