【发布时间】:2022-01-17 11:10:03
【问题描述】:
我正在尝试使用以下代码使用无服务器框架构建一个 express rest-api。我对路径 /fruits 有一个有效的 POST 请求方法,但以下 GET 请求方法会引发 502 Bad Gateway 错误。
const serverless = require('serverless-http');
const express = require('express');
const app = express();
const AWS = require('aws-sdk');
...
const dynamoDB = new AWS.DynamoDB.DocumentClient();
app.get('/fruits/:fruitName', (req, res) => {
const params = {
TableName: TABLE_NAME,
Key: {
fruitName: req.params.fruitName,
},
}
dynamoDB.get(params, (err, res) => {
if (err) {
console.log(error);
res.status(400).json({ error: 'Could not get fruit' });
}
if (res.Item) {
const { fruitName, biName} = res.Item;
res.json({ fruitName, biName});
} else {
res.status(404).json({ error: "Fruit not found" });
}
})
})
...
module.exports.handler = serverless(app);
我已经设置了一个 serverless.yml 如下
provider:
name: aws
runtime: nodejs12.x
stage: dev
region: us-west-2
iamRoleStatements:
- Effect: 'Allow'
Action:
- dynamodb:Query
- dynamodb:Scan
- dynamodb:GetItem
- dynamodb:PutItem
- dynamodb:UpdateItem
- dynamodb:DeleteItem
Resource:
- { "Fn::GetAtt": ["FruitsTable", "Arn" ] }
environment:
TABLE_NAME: 'fruits'
resources:
Resources:
FruitsTable:
Type: 'AWS::DynamoDB::Table'
DeletionPolicy: Retain
Properties:
AttributeDefinitions:
- AttributeName: fruitName
AttributeType: S
KeySchema:
- AttributeName: fruitName
KeyType: HASH
ProvisionedThroughput:
ReadCapacityUnits: 1
WriteCapacityUnits: 1
TableName: 'fruits'
functions:
app:
handler: index.handler
events:
- httpApi: 'GET /fruits/{fruitName}'
- httpApi: 'POST /fruits'
非常感谢任何帮助。
【问题讨论】:
-
愚蠢的问题:但你能把
events部分修改成更像下面这样:- httpApi: 'POST /fruits' - httpApi: 'GET /fruits/{proxy+}'serverless.com/framework/docs/providers/aws/guide/events/… -
@Norman 好的,我已经修改了。
标签: amazon-web-services express aws-lambda amazon-dynamodb serverless-framework