简体   繁体   English

AWS Lambda function 使用 HTTP 模块未发出任何请求

[英]AWS Lambda function using HTTP module not making any request

I have a AWS Lambda function using Node.js 12.x.我有一个使用 Node.js 12.x 的 AWS Lambda function。 Here is my code:这是我的代码:

exports.handler =  async function(event, context) {
const https = require('https');

const sheetId = 01234;

const testData = JSON.stringify({"toTop":true, "cells": [ {"columnId": 3148210723153796, "value": 'TEST'} ] });

const options = {
    hostname: 'api.website.com',
    port: 443,
    path: `/logs`,
    method: 'POST',
    headers: {
        'Content-Type': 'application/json',
        'Authorization': 'Bearer oefohjeoiefoijn'
    }
};

const req = https.request(options, (res) => {
    console.log(`STATUS: ${res.statusCode}`);
    console.log(`HEADERS: ${JSON.stringify(res.headers)}`);
    res.setEncoding('utf8');
    res.on('data', (chunk) => {
        console.log(`BODY: ${chunk}`);
    });
    res.on('end', () => {
        console.log('No more data in response.');
    });
});

req.on('error', (e) => {
    console.error(`problem with request: ${e.message}`);
});

// Write data to request body
req.write(testData);
req.end();
}

The request is not being executed.请求没有被执行。 I am not receiving any errors in Cloudwatch.我在 Cloudwatch 中没有收到任何错误。 The exact code (with the Handler export removed) is working fine in Node.js 12.x on my machine.确切的代码(删除了处理程序导出)在我的机器上的 Node.js 12.x 中运行良好。

Your lambda function terminates before the response is received because you're not waiting for the callback to return.您的 lambda function 在收到响应之前终止,因为您没有等待回调返回。

You can wrap your request into a promise:您可以将您的请求包装到 promise 中:

exports.handler = async function(event, context) {

    return new Promise((resolve, reject) => {

        const req = https.request(options, (res) => {
          // ...
          resolve();
        });

        req.on('error', (e) => {
            reject();
        });

        req.write(testData);
        req.end();
    });
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM