[英]AWS API gateway timeouts
我已经使用 lambdas 和 api 网关在 AWS 上设置了无服务器环境。 我有一个脚本,每当有人在联系表上填写信息时都会调用它。 脚本本身如下所示:
const rp = require('request-promise')
const sendEmail = require('./sendEmail')
module.exports.run = async (event, context, callback) => {
const body = JSON.parse(event.body)
const { name, email, budget, message, attachment } = body
if (!name) {
return callback(null, {
statusCode: 400,
body: JSON.stringify({ message: 'Name is required' }),
})
}
if (!email) {
return callback(null, {
statusCode: 400,
body: JSON.stringify({ message: 'Email address is required' }),
})
}
if (!message) {
return callback(null, {
statusCode: 400,
body: JSON.stringify({ message: 'Message is required' }),
})
}
return Promise.all([
sendEmail({
to: 'Example <user@example.com>',
subject: 'Received submission',
data:
'Hello'
}),
sendEmail({
to: `${name} <${email}>`,
subject: 'Subject',
data:
'Example text',
}),
])
.then(() => {
return callback(null, {
statusCode: 200,
headers: {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Credentials': true,
},
body: JSON.stringify({ message: 'Great success' }),
})
})
.catch(err => {
return callback(null, {
statusCode: 500,
body: JSON.stringify({
message: 'Oh no :( Message not delivered',
error: err,
}),
})
})
}
这是我的 sendEmail 课程
const AWS = require('aws-sdk')
const ses = new AWS.SES()
module.exports = function({ to, subject, data, replyTo }) {
return ses
.sendEmail({
Destination: { ToAddresses: [to] },
Message: {
Body: {
Text: { Charset: 'UTF-8', Data: data },
},
Subject: {
Data: subject,
Charset: 'UTF-8',
},
},
Source: 'Example <user@example.com>',
ReplyToAddresses: [replyTo],
})
.promise()
}
但是,由于超时限制为 aws 方面的五分钟,它一直挂起,我是否遗漏了超过五分钟的时间?
问题是 lambda 位于 eu-west-2,而 SES 设置在 eu-west-1,这意味着它无法联系 SES 中 eu-west-2 中的 api 端点,导致响应 500 .
我在这里看到两个问题。
您可以简单地返回输出,而不是使用回调。 我还将承诺语法更改为 async/await。
const sendEmail = require('./sendEmail')
module.exports.run = async (event, context) => {
const body = JSON.parse(event.body)
const { name, email, budget, message, attachment } = body
if (!name) {
return {
statusCode: 400,
body: JSON.stringify({ message: 'Name is required' }),
}
}
if (!email) {
return {
statusCode: 400,
body: JSON.stringify({ message: 'Email address is required' }),
}
}
if (!message) {
return {
statusCode: 400,
body: JSON.stringify({ message: 'Message is required' }),
}
}
try {
await Promise.all([
sendEmail({
to: 'Example <user@example.com>',
subject: 'Received submission',
data:
'Hello'
}),
sendEmail({
to: `${name} <${email}>`,
subject: 'Subject',
data:
'Example text',
}),
]);
return {
statusCode: 200,
headers: {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Credentials': true,
},
body: JSON.stringify({ message: 'Great success' }),
}
} catch (err) {
return {
statusCode: 500,
body: JSON.stringify({
message: 'Oh no :( Message not delivered',
error: err,
}),
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.