【问题标题】:AWS lambda http post request failingAWS lambda http 发布请求失败
【发布时间】:2019-09-30 09:23:34
【问题描述】:
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 post 请求。将数据发送到指定的 URL。但它是异步的并给出响应消息 null 它没有打印消息“数据已发送”。 如何完成这项工作?提前致谢

【问题讨论】:

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


    【解决方案1】:

    尝试像这样更改您的代码:

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

    【讨论】:

    • TypeError: http.post is not a function at sendFileToUrl (/var/task/index.js) at exports.handler (/var/task/index.js) 我使用的是节点版本 8 λ
    • @Kumar 你没忘记const http = require('http');
    • 我做到了。它的第一行。我仍然收到此错误
    • @Kumar 使用http 并不容易,因为它的级别非常低。请参阅更新的答案。如果您的资源是https,则必须将代码更改为const https = require('https')port: 443,
    • 是的,谢谢
    猜你喜欢
    • 1970-01-01
    • 2019-01-09
    • 2017-02-18
    • 2016-06-18
    • 1970-01-01
    • 2017-05-20
    • 1970-01-01
    • 2015-10-27
    相关资源
    最近更新 更多