How to implement normal GET in NodeJS?

Tried a bunch of different modules (request, http, etc.) for queries, but fundamentally it remains a problem can not return data from a function, that is, the query passes the response is returned and to pull it can't (return). The writing on NodeJS only 3 days. There is something related to async, and so on. Please show a complete example of a GET request, which will allow you to work with response in the main body of the code.
June 10th 19 at 15:21
4 answers
June 10th 19 at 15:23
Solution
The easiest
request.get({
 url: someurl
 }, (err, res, body) => {
 if (err || !res || !Res. statusCode || Math.floor(res.statusCode / 100) !== 2) {
 return console.error(err);
}
 asyncFunc(body); // Here give the answer for the other f-AI
});


Wrap in promis
function getReq(someurl) {
 return new Promise((response, reject) => {
request.get({
 url: someurl
 }, (err, res, body) => {
 if (err || !res || !Res. statusCode || Math.floor(res.statusCode / 100) !== 2) {
 return reject(err);
}
 response(body); // Here give the answer for the next promis
});
}
);
}

getReq('https://ya.ru')
 .then((body) => {
console.log(body);
})
 .catch((err) => console.error(err));


On async / await is already on will not be difficult to alter
June 10th 19 at 15:25
require('request')
.get('https://toster.ru/q/488141')
 .on('error', function(err) {
console.error(err);
})
 .on('response', function(res) {
console.log(Res. statusCode);
console.log(Res. headers['content-type']);
})
.pipe(require('fs').createWriteStream('toster.html'))
 .on('finish', function() {
console.log('OK');
 var file = require('fs').readFileSync('toster.html');
console.log(file);
 });
June 10th 19 at 15:27
Read about callback, async (), async await, everything will become clear
June 10th 19 at 15:29

Find more questions by tags JavaScriptNode.jsnpm