3

I'm trying to do a HTTP PUT via node js in AWS lambda, but I keep getting time outs. According to this "A Lambda function with VPC access will not have internet access unless you add a NAT", but in my case I'm not using a VPC.

exports.handler = (event, context) => {
      const options = {
          host: 'xxx',
          path: 'xxx',
          port: 443,
          method: 'PUT'
      };
    req = http.request(options, (res) => {
      console.log(res);
    });
};
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343

3 Answers3

0

The problem is with Lambda node.js.
If you'd like to use node.js version 8, you should write code like this example

exports.handler = async (event, context) => {
  const options = {
      host: 'xxx',
      path: 'xxx',
      port: 443,
      method: 'PUT'
  };
  const response = await http.request(options);
  console.log(response);
};

If you don't want to use node.js version 8, you should add third parameter callback and call it after function execution.

exports.handler = (event, context, callback) => {
  const options = {
      host: 'xxx',
      path: 'xxx',
      port: 443,
      method: 'PUT'
  };
  req = http.request(options, (res) => {
    console.log(res);
    callback();
  });
};
Grynets
  • 2,477
  • 1
  • 17
  • 41
0

The way your code is written, it is not returning anything as a response.

You can do it this way (using callback in node 4, 6 or 8) ...

exports.handler = (event, context, callback) => {
    const options = {
        host: 'xxx',
        path: 'xxx',
        port: 443,
        method: 'PUT'
    };

    return http.request(options, (result) => {
        console.log(result);

        // Calling callback sends "result" to API Gateway.
        return callback(null, result);
    });
};

Or, if you want to use node 8's support for promises...

// You can use `async` if you use `await` inside the function.
// Otherwise, `async` is not needed. Just return the promise.
exports.handler = (event, context) => {
    const options = {
        host: 'xxx',
        path: 'xxx',
        port: 443,
        method: 'PUT'
    };

    return new Promise((resolve, reject) => {
        return http.request(options, result => {
            return resolve(result)
        })
    })
};
Noel Llevares
  • 15,018
  • 3
  • 57
  • 81
0

You need to call req.end() after the request.

const req = http.request(options)
req.end()
Kashif Siddiqui
  • 1,476
  • 14
  • 26