将节点请求模块与AWS Lambda和API Gateway一起使用

时间:2017-06-23 16:50:05

标签: javascript amazon-web-services aws-lambda aws-api-gateway node-request

这个lambda函数有效:

exports.handler = function(event, context, callback) {
  const done = (err, res, func) => callback(null, {
    statusCode: '200',
    body: res,
    headers: { 'Content-Type': 'application/json' },
  })

  done(null, 'works'))
}

我可以点击API网关端点并收到响应消息'works'

但是,当我向Slack添加一个请求调用(POST一条消息给Slack)时,它看起来像这样:

const request = require('request')
const moment = require('moment-timezone')

exports.handler = function(event, context, callback) {
  // the json object is built following these docs:
  // https://api.slack.com/docs/message-attachments
  const SLACK_WEB_HOOK_URL = process.env.SLACK_WEB_HOOK_URL
  const uri = SLACK_WEB_HOOK_URL
  const method = 'POST'
  const options = {
    json,
    uri,
    method,
  }

  const slack = (opts) => {
    request.post(opts, (err, response, body) => {
      if (response.statusCode < 300) {
        return 'Success!'
      } else {
        return 'Err!'
      }
    })
  }

  const done = (err, res, func) => callback(null, {
    statusCode: '200',
    body: res,
    headers: { 'Content-Type': 'application/json' },
  })

  done(null, slack(options))
}

当我点击API终点时服务器挂起......

我收到Task timed out after 10.00 seconds错误:

{
  "errorMessage": "2017-06-23T16:41:21.483Z c385e32e-5832-11e7-8c4f-673b524cf783 Task timed out after 10.00 seconds"
}

但我的Slack POST请求已被发送,我在频道中看到了该消息。

如何发送POST请求然后等待它返回,然后使用自定义响应消息退出lambda函数?

感谢您的帮助!

1 个答案:

答案 0 :(得分:1)

将回调放入post方法

的回调中
request.post(opts, (err, response, body) => {
    if (response.statusCode < 300) {
        return callback(null, {
            statusCode: '200',
            body: res,
            headers: { 'Content-Type': 'application/json' },
        });
    } else {
        return callback(err);
    }
});