How to request a page in Nodejs?

Asked

Viewed 376 times

-3

I would like to know how to request a page using Nodejs. Basically, I need to make a request to a webservice that provides data of places based on the reported cep and from the answer given (which comes in json format), process the data and perform some operations. I’m a beginner in Ode and I don’t know how to do that. I am using the 4.x express framework in the project. I thank you in advance for your cooperation!

  • The same way you request a page in Apache, IIS, Tomcat... by URL.

  • For you to get started it’s good to see a tutorial: https://code4coders.wordpress.com/2016/10/14/development-uma-application-restful-api-em-node-js-express-js-com-mongodb/ It’s implemented from simple to what you want. As soon as you have any doubt post your code snippet.

2 answers

0

you can use the Xios or superagent to request any API from within your nodejs code

0

You can use the http or https from Ode himself to make the call. This example is using the Mailgun api:

const https = require('https');

const config = require('./config'); // Meu ficheiro de configuração

helpers.email = function (data, callback) {

    if (data) {
        // Payload
        const payload = {
            'from': config.mailGun.defaultEmail,
            'to': data.email,
            'subject': data.orderId,
            'text': data.body

        };

        var stringPayload = queryString.stringify(data);


        // Request options
        const requestOptions = {
            'protocol': 'https:',
            'hostname': 'api.mailgun.net',
            'path': `/v3/${config.mailGun.sandboxDomain}/messages`,
            'method': 'POST',
            'headers': {
                'Authorization': `Basic ${Buffer.from(`api:${config.mailGun.apiKey}`).toString('base64')}`,
                'Content-Type': 'application/x-www-form-urlencoded',
                'Content-Length': Buffer.byteLength(stringPayload)

            }
        }
            //making a request
        var req = https.request(requestOptions, res => {
            var status = res.statusCode;
            if (status == 200) {
                callback(status);
                debug(status);
            } else {
                callback(status);
            }
        });
        req.on('data', (data) => {
            callback(data);
        });

        req.on('error', (e) => {
            console.log(e);
            debug('Email failed to send');
        });
        //attaching the  string payload
        req.write(stringPayload);
        //sending the request
        req.end();

    } else {
        callback('missing required fields');
    }



};

Browser other questions tagged

You are not signed in. Login or sign up in order to post.