0

I'm new to node.js, So how to send duration in response in http module i tried sending it through req.write and req.writeHead(), but its not working.Help me with this issue

    var https = require('https');
    const config_KEYS = require('./config.js');

    exports.handler = (event, context, callback) => {

        var userLat = event.userLat;
        var userLong = event.userLong;
        var destinationLat = event.destinationLat;
        var destinationLong = event.destinationLong;
        var params = {
            host:'maps.googleapis.com',
            path: '/maps/api/distancematrix/json?units=imperial&origins='+userLat+","+userLong+'&destinations='+destinationLat+","+destinationLong+'&key='+config_KEYS.GOOGLE_API_KEY+'&departure_time=now'
        };
        var req = https.request(params, function(res) {
            let data = '';
            console.log('STATUS: ' + res.statusCode);
            // res.setEncoding('utf8');
            res.on('data', function(chunk) {
                data += chunk;
            });
            res.on('end', function() {
                console.log("DONE");

                const parsedData = JSON.parse(data);
                console.log("data ===>>>>",parsedData);
                var duration = parsedData.rows[0].elements[0].duration_in_traffic.text;
           var obj = {}
            obj.duration = duration
            res.end(duration) ;

            });

        });
        req.write(callback)
        req.end();
    };
Sandy
  • 1
  • 1

1 Answers1

0

In node js https there is one method like res.end() to send data after https request ends

Example:

const https = require('https');
const fs = require('fs');

const options = {
  pfx: fs.readFileSync('test/fixtures/test_cert.pfx'),
  passphrase: 'sample'
};

https.createServer(options, (req, res) => {
  res.writeHead(200);
  res.end('hello world\n');
}).listen(8000);

Here what you want to achieve is use function in res.on('end', ) and then return to that function. So, In your case it will not send in res.on('end', ) because untimately you're returning a value to function not a method.

Here is the solution:

const parsedData = JSON.parse(data);
console.log("data ===>>>>",parsedData);
var duration = parsedData.rows[0].elements[0].duration_in_traffic.text;
req.end('duration');

one more way is you can use callback. For the reference I am providing one link

Callback https

Harsh Patel
  • 4,208
  • 6
  • 24
  • 55