如何在hhtp模块中发送响应

时间:2019-01-10 07:11:40

标签: node.js

我是node.js的新手,所以如何在http模块中发送响应时长,我尝试通过req.write和req.writeHead()将其发送,但无法正常工作。请帮我解决这个问题

    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();
    };

1 个答案:

答案 0 :(得分:0)

在节点js https中,有一种类似res.end()的方法可以在https请求结束后发送数据

示例:

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);

您要实现的是在res.on('end',)中使用函数,然后返回该函数。因此,在您的情况下,它将不会发送res.on('end',),因为很遗憾您返回的是函数的值而不是方法。

这是解决方案:

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

另一种方法是可以使用回调。作为参考,我提供了一个链接

Callback https