Lambda - Make an HTTPS request blueprint - not working

0

I'm attempting to use the Lambda Make an HTTPS request blueprint as a starting point to request a JSON response from an API.

function from blueprint

After I created the function I set up a test event. With something like the following.

{ "options": { "headers": { "Authorization": "Bearer key-here" }, "host": "my.host.here", "path": "/my/path/here" } }

I can't share the actual values as the API requires a key. I have no trouble using CURL or Postman to make a call to the API so I know the API works.

When I test the function I get the following error.

Response { "errorType": "TypeError", "errorMessage": "The "chunk" argument must be of type string or an instance of Buffer or Uint8Array. Received undefined", "trace": [ "TypeError [ERR_INVALID_ARG_TYPE]: The "chunk" argument must be of type string or an instance of Buffer or Uint8Array. Received undefined", " at new NodeError (node:internal/errors:405:5)", " at write_ (node:_http_outgoing:875:11)", " at ClientRequest.write (node:_http_outgoing:834:15)", " at Runtime.handler (file:///var/task/index.mjs:42:9)", " at Runtime.handleOnceNonStreaming (file:///var/runtime/index.mjs:1173:29)" ] }

Function Logs START RequestId: 1e79244e-1d9a-42fd-baf6-b91179268805 Version: $LATEST 2024-04-21T00:16:37.425Z 1e79244e-1d9a-42fd-baf6-b91179268805 ERROR Invoke Error {"errorType":"TypeError","errorMessage":"The "chunk" argument must be of type string or an instance of Buffer or Uint8Array. Received undefined","code":"ERR_INVALID_ARG_TYPE","stack":["TypeError [ERR_INVALID_ARG_TYPE]: The "chunk" argument must be of type string or an instance of Buffer or Uint8Array. Received undefined"," at new NodeError (node:internal/errors:405:5)"," at write_ (node:_http_outgoing:875:11)"," at ClientRequest.write (node:_http_outgoing:834:15)"," at Runtime.handler (file:///var/task/index.mjs:42:9)"," at Runtime.handleOnceNonStreaming (file:///var/runtime/index.mjs:1173:29)"]} END RequestId: 1e79244e-1d9a-42fd-baf6-b91179268805 REPORT RequestId: 1e79244e-1d9a-42fd-baf6-b91179268805 Duration: 216.36 ms Billed Duration: 217 ms Memory Size: 128 MB Max Memory Used: 69 MB Init Duration: 192.81 ms

Instead of using the test event I created an option constant and replaced event.options in the code to bypass possible errors in my test event JSON. Still got the chunk error.

I even tried a string with URL to an API I know that works, needs no authorization, and used that as the first parameter to https.request. No joy.

Can someone try the blueprint and show me test event JSON that works for an API you know that is open? I can usually work from a working example.

Thanks for any help.

creedon
asked 13 days ago162 views
1 Answer
2
Accepted Answer

Hello.

I'm not sure what kind of code your Lambda function has, but if you keep the default code, I think you can make a request with the event JSON below.
Even if there is no need to include a body in the request, we specify an empty field by including ""data": {},".

{
  "data": {},
  "options": {
    "hostname": "www.google.com"
  }
}

The code below is generated by Lambda by default, but uses "data" in "req.write(JSON.stringify(event.data));".

import * as https from 'node:https';

/**
 * Pass the data to send as `event.data`, and the request options as
 * `event.options`. For more information see the HTTPS module documentation
 * at https://nodejs.org/api/https.html.
 *
 * Will succeed with the response body.
 */
export const handler = (event, context, callback) => {
    const req = https.request(event.options, (res) => {
        let body = '';
        console.log('Status:', res.statusCode);
        console.log('Headers:', JSON.stringify(res.headers));
        res.setEncoding('utf8');
        res.on('data', (chunk) => body += chunk);
        res.on('end', () => {
            console.log('Successfully processed HTTPS response');
            // If we know it's JSON, parse it
            if (res.headers['content-type'] === 'application/json') {
                body = JSON.parse(body);
            }
            callback(null, body);
        });
    });
    req.on('error', callback);
    req.write(JSON.stringify(event.data));
    req.end();
};
profile picture
EXPERT
answered 13 days ago
profile picture
EXPERT
reviewed 12 days ago
profile picture
EXPERT
reviewed 13 days ago
  • Thank you Riku! The data key was what was missing from my latest run at the code/test event. I thought I had seen another message of yours where you suggested a similar fix and given that a try. Obviously I didn't get it right before! :-)

    For others following on, I started from scratch with a new function with the blueprint code and then used Riku's JSON and bingo!

    If some AWS Lambda folks see this. Have you considered supplying working test event JSON as part of the blueprint so the blueprint is complete/functioning/starter code?

  • Oh the excitement! I have the test code calling into the API needed and a response is returned!

    Thanks again!

You are not logged in. Log in to post an answer.

A good answer clearly answers the question and provides constructive feedback and encourages professional growth in the question asker.

Guidelines for Answering Questions