Don Diego
Don Diego

Reputation: 1488

get data from an URL with promise in nodejs

I'm pretty new with nodejs, and I'm trying to get data from an URL and return to the HTML page.

For now, the server.js, routes.js and controller.js files, and in the controller.js I'm trying to do this:

'use strict';

const https = require('https');
var mongoose = require('mongoose'),


exports.operations = function(req, res) {
var result;
    
    https.get('https://my/link', (res) => {
  

    res.on('data', (d) => {
        //process.stdout.write(d);
        result += d;
    });

    res.on('end', () => {
        console.log("HERE ", result);
      });

    }).on('error', (e) => {
    console.error(e);
    });

Anyway, I think that if I want to send the result to the html, adding before the last }); the line

res.render('index', { title: 'Hey', message: JSON.stringify(result, null, 4) });

then I need to use promises, like .then() or similar. But I absolutely don't get how to make it on nodejs (I knew how to do in angularJS anyway).

How can I get it to work?

UPDATE: any suggestions about libraries to use are welcome!

Upvotes: 0

Views: 299

Answers (1)

UsmanJ
UsmanJ

Reputation: 1299

I would recommend using Axios for http requests.

It is fairly self explanatory to use. An example of this is:

axios.get('/user', {
    params: {
      ID: 12345
    }
  })
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  })
  .then(function () {
    // always executed
  });  

Upvotes: 1

Related Questions