I am learning about callback functions and API - node.js

Here I am learning about Callback functions and API to make weather app on node but when I am running the app on Terminal it says undefined I don't know why?
const request = require("request");
request({
URL: "http://maps.googleapis.com/maps/api/geocode/json?address=1301%20lombard%20street%20philadelphia",
json: true
}, (error, response, body) => {
console.log(body);
});

You are calling request incorrectly. You need to call it like so:
request("http://maps.googleapis.com/maps/api/geocode/json?address=1301%20lombard%20street%20philadelphia", {
json: true
}, (error, response, body) => {
console.log(body);
});
alternatively
request({
url: "http://maps.googleapis.com/maps/api/geocode/json?address=1301%20lombard%20street%20philadelphia",
json: true
}, (error, response, body) => {
console.log(body);
});
Notice the url property in lowercase, whereas yours was uppercase
Refer to https://github.com/request/request#requestoptions-callback

Related

How to correctly use a callback function in NodeJS

Alright. Trying to make a very simple request here. First code with asynchronous Nodejs. According to everywhere I've checked, I'm doing this right. None of them explained really how callbacks work, they just say what to do, so I have no way of figuring it out intuitively.
const request = require("request");
function fetchData(url, json, callback) {
request({
url: url,
json: json,
method: "get"
}, callback(error, response, body))
}
console.log(fetchData("https://www.yahoo.com", false, function(error, response, body) {
if(!error && response.statusCode == 200) {
return body;
} else {
return error;
}
}));
Thanks
Two things- first, pass the callback variable into request(), don't call the function.
callback vs callback()
Second, you can't use the return value from the callback function. Call console.log() from inside the callback function.
Code with changes:
const request = require("request");
function fetchData(url, json, callback) {
request({
url: url,
json: json,
method: "get"
}, callback)
}
fetchData("http://www.yahoo.com", false, function(error, response, body) {
if(!error && response.statusCode == 200) {
console.log(body);
} else {
console.log(error);
}
}));

Unable to access response object data outside the function in node js

I am using node js and making a call to spotify API and receive the response in body object, as shown in below code:
var options = {
url: 'https://api.spotify.com/v1/me',
headers: { 'Authorization': 'Bearer ' + access_token },
json: true
};
request.get(options, function(error, res, body) {
console.log(body)
});
This gives me output:
But now when I try to access the body object outside the function I get undefined. I think the problem is that I am making an asynchronous call and so before the response is received the statements where I make use of body variable outside function are executed. But I am a bit confused about how to get to the solution.
Any help is appreciated
Edit:
request.get(options, function(error, res, body) {
console.log(body)
response.render('user_account.html', {
data: body
})
});
And it gives the output:
Use promise.
You can try following:
const apiCall = () => {
return new Promise((resolve, reject) => {
var options = {
url: 'https://api.spotify.com/v1/me',
headers: { 'Authorization': 'Bearer ' + access_token },
json: true
};
request.get(options, function(error, res, body) {
if(error) reject(error);
console.log(body);
resolve(body);
});
});
}
apiCall().then((body) => {
// do your things here
})
.catch((err) => console.log(err));

How to pass the information from function in the Express get API in MEAN Stack

Here I have a function hsResponse which is as below and in the console.log I am getting the proper body response when I run this standalone, but now I wanted call inside the app.get() method and I wanted to put the response of hsResponse to the app.get() API response.
After running the API I wanted to get the body (the value which is printed in the console.log) of hsResponse instead of Root API.
How can I achieve this?
var hsResponse = request({
proxy: proxyUrl,
url: request_data.url,
headers: request_data.headers,
method: request_data.method,
form: oauth.authorize(request_data)
}, function (error, response, body) {
console.log(body);
});
app.get('', (req, res) => {
res.send('Root API');
});
Why not use a function with a callback passed in parameter to handle the request result:
var hsResponse = function (done) {
// done is a function, it will be called when the request finished
request({
proxy: proxyUrl,
url: request_data.url,
headers: request_data.headers,
method: request_data.method,
form: oauth.authorize(request_data)
}, function (error, response, body) {
if (error) return done(error);
done(null, body);
});
}
app.get('', (req, res) => {
hsResponse( function (err, body) {
if (err) throw err;
// get body here
res.send('Root API');
} );
});
Edit the code above buffers up the entire api response into memory (body) for every request before writing the result back to clients, and it could start eating a lot of memory if there were many requests at the same time. Streams, by using streams we could read one chunk at a time from the api response, store it into memory and send it back to the client:
app.get('', (req, res) => {
request({
proxy: proxyUrl,
url: request_data.url,
headers: request_data.headers,
method: request_data.method,
form: oauth.authorize(request_data)
}).pipe(res);
});
Reference: stream handbook
You can just put the code inside:
app.get('', (req, res) => {
var hsResponse = request({
proxy: proxyUrl,
url: request_data.url,
headers: request_data.headers,
method: request_data.method,
form: oauth.authorize(request_data)
}, function (error, response, body) {
res.send(body); //<-- send hsResponse response body back to your API consumer
});
});

Request within a request in nodejs

I am using request library in nodejs. I need to call new url within the request but I am not able to join the response as it is asynchronouse. How do I send variable a as in below request containing result of request within a request.
request({
url: url,
json: true
}, function (error, response, body) {
var a = [];
a.push(response);
for (i = 0; i < a.length; i++) {
if (a.somecondition === "rightcondition") {
request({
url: url2,
json: true
}, function (error, response, body) {
a.push(response);
});
}
}
res.send(a);
});
Your code seems almost right for what you want. You are just sending the response in the wrong callback. Move it so it only sends after the second request has completed:
request({
url: url,
json: true
}, function (error, response, body) {
var a = [];
a.push(response);
request({
url: url2,
json: true
}, function (error, response, body) {
for(i=0;i<a.length;i++){
if(a.somecondition === "rightcondition"){
a.push(response);
}
}
res.send(a); // this will send after the last request
});
});
You can use async waterfall
'use strict';
let async = require('async');
let request = require('request');
async.waterfall([function(callback) {
request({
url: url,
json: true
}, function(error, response, body) {
callback(error, [response]);
});
}, function(previousResponse, callback) {
request({
url: url2,
json: true
}, function(error, response, body) {
for(i=0;i<previousResponse.length;i++){
if(previousResponse.somecondition === "rightcondition"){
previousResponse.push(response);
}
}
callback(error, previousResponse);
});
}], function(err, results) {
if (err) {
return res.send('Request failed');
}
// the results array will be final previousResponse
console.log(results);
res.send(results);
});

Alternative for .then() after request()

I'm new to NodeJS. I have an asynchronous function
request({url: 'url',json: true}, function (error, response, body) {});
I want to call a function only after this function is invoked. I can't call a .then() here. What are the other alternatives for this situation?
You could try something like this
return new Promise(resolve => {
request({
url: "",
method: "",
headers: {},
json: true
}, function (error, response, body) {
if(!error)
resolve(body);
})
}).then(value => {
// process value here
})
Just pass it as your callback function:
function callback (err, res, body) {
// Do what needs to be done here.
}
request({ url: 'url', json: true, someParam: true }, callback);
At the beginning of your callback function, check if err exists and if so, handle the error.
This article might help you.
You can only call then if your asynchronous function returns a Promise. But before you get into Promises, you should know the basics about Node.js.

Resources