I am trying to make a very simple get request from a plugin I'm developing. I have tried a couple of things. Attached is an excerpt of some of this code.
const request = require('request');
function getRandom() {
return Math.random() * 10;
}
function getInfo() {
let info;
console.log("magic happens here")
request('http://google.com', function (err, res, body) {
info = body.toString();
});
return info;
}
export default function (server) {
server.route({
path: '/yoinfo',
method: 'GET',
handler(req, reply) {
reply({ info: getInfo(), name: "jimbo", rand: getRandom() });
}
});
}
Both name and rand are returned in the payload, but info is not. Any idea how I can make a simple http get request within the plugin server directory?
In the first example your call to getInfo() needs to wait for request() to call the callback before returning. The callback is called asynchronously, so you'll need to use a promise or another callback to get this working.
const request = require('request');
function getRandom() {
return Math.random() * 10;
}
function getInfo(callback) {
console.log("magic happens here")
request('http://google.com', function (error, res, body) {
if (error) {
// always check for errors
callback(error);
// return to prevent the rest of this function from running
return;
}
// pass the body to the callback without an error
callback(null, body.toString());
});
}
export default function (server) {
server.route({
path: '/yoinfo',
method: 'GET',
handler(req, reply) {
// call getInfo and it will call getInfoCallback() when it is done
getInfo(function getInfoCallback(error, info) {
if (error) {
// always check for errors
reply(error);
return
}
reply({
info: info,
name: "jimbo",
rand: getRandom()
});
});
}
});
}
Apache, Apache Lucene, Apache Hadoop, Hadoop, HDFS and the yellow elephant
logo are trademarks of the
Apache Software Foundation
in the United States and/or other countries.