简体   繁体   中英

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. 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. 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. Obs.: I'm new to Node, tried with this tutorial: https://www.twilio.com/blog/2017/08/http-requests-in-node-js.html . The "url" and "key are masked here for security reasons. Any help is fine to me, I'm grateful.

The problem is that on request.get line you have your URL and headers templates

`${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.

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

Or, with ES6 shorthand:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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