AWS Lambda http发布请求失败

时间:2019-05-13 12:04:03

标签: node.js http asynchronous lambda aws-lambda

const http = require('http');

exports.handler = function (event, context, callback) {
console.log(event);
var data = {
    'name': 'test'
};
var url = "http://**************.com";
function sendFileToUrl(url, data, context, callback) {
    console.log('Sending File to the URL:' + url);
    if (url && data && context) {
        if (context) {
            setInterval(function () { }, 1000);
            context.callbackWaitsForEmptyEventLoop = false;
        }
        return http.post(url, JSON.stringify(data)).then(function (res) {
            console.log("Data Sent & response: " + res.statusCode);
            callback(null, 'success msg');
        }).on('error', function (e) {
            console.log("Could not send the data & error: " + e.message);
            callback(new Error('failure'));
        });
    }
}
return sendFileToUrl(url, data, context, callback);

};

我正在尝试从lambda发出http发布请求。将数据发送到指定的URL。但是它是异步的,并且给出的响应消息为空 它不打印消息“数据已发送”。 如何做到这一点?预先感谢

1 个答案:

答案 0 :(得分:0)

尝试这样更改代码:

const http = require('http');

exports.handler = function (event, context, callback) {
    console.log(event);
    var data = JSON.stringify({
        'name': 'test'
    });    
    const options = {
      hostname: 'example.com',
      path: '/path-to-resource',
      port: 80,
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Content-Length': data.length
      }
    };

    function sendFileToUrl(options, data, callback) {
        console.log('Sending File to the URL:' + url);
        if (url && data) {
            const req = http.request(url, JSON.stringify(data)).then(function (res) {
                console.log("Data Sent & response: " + res.statusCode);
                callback(null, 'success msg');
            });            
            req.on('error', function (e) {
                console.log("Could not send the data & error: " + e.message);
                callback(new Error('failure'));
            });            
            req.write(data);
            req.end();
        }
    }
    sendFileToUrl(options, data, callback);
};