I'm trying to get the response of one request in nodeJS, but I cant get it yet. Can you help me please? This is the code:
var options = {
'method': 'GET',
'url': 'https://api.web.com/v1/prospects?search=12345&api-key=123456',
'headers': {
}
};
request(options, function (error, response) {
if (error)throw new Error(error);
var result = response.body;
});
console.log(result);
and this is what I got:
(node:14848) UnhandledPromiseRejectionWarning: ReferenceError: result is not defined
Well, that's because result is not defined in the scope you are using it.
let result;
request(options, function (error, response) {
if (error)throw new Error(error);
result = response.body;
});
console.log(result);
However, even this doesn't make sense, because the request
call is asynchronous, and result
will not be set when using in the console.log
. You probably want:
request(options, function (error, response) {
if (error) throw new Error(error);
const result = response.body;
console.log(result);
});