I’m developing a node.js app. What I’m trying to do is get the getBody() function to return the body of response the URL. The way I’ve written this would obviously only return the request function and not what the request function returns. I wrote that to show where I’m stuck.
var request = require('request');
var Body = function(url) {
this.url = url;
};
Body.prototype.getBody = function() {
return request({url:this.url}, function (error, response, body) {
if (error || response.statusCode != 200) {
console.log('Could not fetch the URL', error);
return undefined;
} else {
return body;
}
});
};
Assuming the
requestfunction is asynchronous, you won’t be able to return the result of the request.What you can do is have the
getBodyfunction receive a callback function that is invoked when the response is received.So you’d use it like this…