0
votes

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.

2
what do you get in the response?Henrique Forlani

2 Answers

0
votes

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) => { ... });
0
votes

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