AWS Lambda 返回“内部服务器错误”

时间:2021-07-28 19:40:42

标签: node.js amazon-web-services aws-lambda

我的版本 Node.js 14.x 使用 https.request 时返回“内部服务器错误”:

const https = require('https');
exports.handler = async(event) => {
 console.log(event);
 let dataString = ''

 const response = await new Promise((resolve, reject) => {
     const { pathParameters } = event;
     if (!pathParameters || !pathParameters.id) {
         resolve({
             statusCode: 400,
             body: 'Please provide a id!'
         })
     }
     const options = {
         hostname: 'pokeapi.co',
         path: `/api/v2/pokemon/${pathParameters.id}`,
         port: 443,
         method: 'GET',
         headers: { 'Content-Type': 'application/json' }
     };
     const req = https.request(options, function(res) {
         res.on('data', chunk => {
             console.log(chunk);
             dataString += chunk;
         });
         res.on('end', () => {
             resolve({
                 statusCode: 200,
                 body: JSON.stringify(JSON.parse(dataString), null, 4)
             });
         });
     });

     req.on('error', (e) => {
         reject({
             statusCode: 500,
             body: 'Something went wrong!'
         });
     });
 });

 return response
;};

https.get 运行良好:

const https = require('https');
exports.handler = async(event) => {
    console.log(event);
    let dataString = ''

    const response = await new Promise((resolve, reject) => {
        const { pathParameters } = event;
        if (!pathParameters || !pathParameters.id) {
            resolve({
                statusCode: 400,
                body: 'Please provide a id!'
            })
        }

        const req = https.get(`https://pokeapi.co/api/v2/pokemon/${pathParameters.id}`, function(res) {
            res.on('data', chunk => {
                console.log(chunk);
                dataString += chunk;
            });
            res.on('end', () => {
                resolve({
                    statusCode: 200,
                    body: JSON.stringify(JSON.parse(dataString), null, 4)
                });
            });
        });

        req.on('error', (e) => {
            reject({
                statusCode: 500,
                body: 'Something went wrong!'
            });
        });
    });

    return response;
};

{pathParameters.id} 这是我从网关获得的 ID,我需要在函数中处理它。我必须马上说,这不是因为路径中的引号而不是端口中的引号。 CloudWatch 日志中没有错误。我正在将 lambda 函数连接到 AWS 网关 http。

START RequestId: 86503ade-fd54-400a-bd39-d58cd9d5cc45 Version: $LATEST
2021-07-28T19:21:37.826Z    86503ade-fd54-400a-bd39-d58cd9d5cc45    INFO    {
  version: '2.0',
  routeKey: 'GET /api/schedule/quest/{id}',
  rawPath: '/dev/api/schedule/quest/1',
  rawQueryString: '',
  headers: {
    accept: 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
    'accept-encoding': 'gzip, deflate, br',
    'accept-language': 'en-US,en;q=0.5',
    'cache-control': 'max-age=0',
    'content-length': '0',
    host: 'hkh9lnprbf.execute-api.eu-central-1.amazonaws.com',
    'upgrade-insecure-requests': '1',
    'user-agent': 'Mozilla/5.0 (X11; Linux x86_64; rv:78.0) Gecko/20100101 Firefox/78.0',
    'x-amzn-trace-id': 'Root=1-6101ae41-697bf7894a7c98d73f84bf31',
    'x-forwarded-for': '78.85.49.90',
    'x-forwarded-port': '443',
    'x-forwarded-proto': 'https'
  },
  requestContext: {
    accountId: '617260961257',
    apiId: 'hkh9lnprbf',
    domainName: 'hkh9lnprbf.execute-api.eu-central-1.amazonaws.com',
    domainPrefix: 'hkh9lnprbf',
    http: {
      method: 'GET',
      path: '/dev/api/schedule/quest/1',
      protocol: 'HTTP/1.1',
      sourceIp: '78.85.49.90',
      userAgent: 'Mozilla/5.0 (X11; Linux x86_64; rv:78.0) Gecko/20100101 Firefox/78.0'
    },
    requestId: 'DMgqTgDpliAEQzg=',
    routeKey: 'GET /api/schedule/quest/{id}',
    stage: 'dev',
    time: '28/Jul/2021:19:21:37 +0000',
    timeEpoch: 1627500097792
  },
  pathParameters: { id: '1' },
  isBase64Encoded: false
}
END RequestId: 86503ade-fd54-400a-bd39-d58cd9d5cc45
REPORT RequestId: 86503ade-fd54-400a-bd39-d58cd9d5cc45  Duration: 3004.50 ms    Billed Duration: 3000 ms    Memory Size: 128 MB Max Memory Used: 17 MB  
2021-07-28T19:21:40.823Z 86503ade-fd54-400a-bd39-d58cd9d5cc45 Task timed out after 3.00 seconds

这不是解决方案,但现在我在听完有关增加超时的答案后看到日志中出现错误。

2021-07-29T04:59:26.187Z    8536861f-b6e8-46fd-8c9b-93a060be47bb    ERROR   Invoke Error    
{
    "errorType": "Error",
    "errorMessage": "[object Object]",
    "stack": [
        "Error: [object Object]",
        "    at _homogeneousError (/var/runtime/CallbackContext.js:12:12)",
        "    at postError (/var/runtime/CallbackContext.js:29:54)",
        "    at done (/var/runtime/CallbackContext.js:58:7)",
        "    at fail (/var/runtime/CallbackContext.js:70:7)",
        "    at /var/runtime/CallbackContext.js:106:16",
        "    at processTicksAndRejections (internal/process/task_queues.js:95:5)"
    ]
}

我还找到了一种解决方法,使用 http.get(option, function (res) {..... 代替 http.reguest(option, function (res) {.....

1 个答案:

答案 0 :(得分:2)

您的 Lambda 在默认 3 秒后超时:

2021-07-28T19:21:40.823Z 86503ade-fd54-400a-bd39-d58cd9d5cc45 Task timed out after 3.00 seconds

您需要在 AWS 控制台(AWS Lambda -> Functions -> function_name -> General configuration -> Edit and set timeout)中或通过您的部署方法增加此项。

相关问题