【问题标题】:Lambda/nodejs http put timing out with no VPC set up未设置 VPC 的 Lambda/nodejs http 超时
【发布时间】:2019-06-06 06:55:37
【问题描述】:

我正在尝试通过 AWS lambda 中的节点 js 执行 HTTP PUT,但我一直在超时。根据this“除非您添加 NAT,否则具有 VPC 访问权限的 Lambda 函数将无法访问 Internet”,但就我而言,我没有使用 VPC。

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

【问题讨论】:

  • 能否请您添加完整的 lambda 函数代码?
  • @Grynets 当然,刚刚添加。
  • 你说你正在做一个 POST,但我在代码中看到了 PUT……这可能是原因吗?
  • @CaioDornellesAntune 刚刚修复了文本,我实际上是指 PUT。

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


【解决方案1】:

按照您的代码编写方式,它不会返回任何响应。

您可以这样做(在node 4、6 或8 中使用callback)...

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);
    });
};

或者,如果你想使用node 8 对承诺的支持...

// 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)
        })
    })
};

【讨论】:

    【解决方案2】:

    问题在于 Lambda node.js。
    如果你想使用 node.js 版本 8,你应该写这样的代码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);
    };
    

    如果不想使用node.js 8版本,需要添加第三个参数callback,在函数执行后调用。

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

    【讨论】:

      猜你喜欢
      • 2020-12-16
      • 2017-10-13
      • 1970-01-01
      • 1970-01-01
      • 2017-04-06
      • 2020-12-15
      • 1970-01-01
      • 2020-05-13
      • 2020-08-07
      相关资源
      最近更新 更多