0

My version Node.js 14.x When using https.request return "Internal Server Error" :

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 works well :

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} this is the id that I get from the gateway and I need to handle it in a function. I must say right away that this is not because of the quotes in the path and not in the port. There are no errors in the CloudWatch logs. I am connecting lambda function to AWS gateway 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

This is not a solution, but now I see an error in the logs after listening to the answer about increasing the timeout.

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)"
    ]
}

I also found a workaround using http.get(option, function (res) {..... instead of http.reguest(option, function (res) {.....

2
  • I'd be tempted to add an exception handler and console.log anything thrown. Commented Jul 28, 2021 at 20:09
  • I think CloudWatch gives me comprehensive information. Commented Jul 29, 2021 at 6:28

1 Answer 1

2

Your Lambda is timing out after the default 3 seconds:

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

You'll need to increase this in either the AWS console (AWS Lambda -> Functions -> function_name -> General configuration -> Edit and set timeout) or via your method of deployment.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.