我正在使用AWS在Nodejs中构建REST API。我期待着Postman的回应,说“
Your Bid Must Be Higher than ${auction.highestBid.amount}
“但是,我在Postman上收到了内部服务器错误,AWS Cloudwatch上的错误如下所示:enter image description here。但是,我在Postman上发送请求,地址为:enter image description here请帮助!!
我期待的回应是:你的出价必须高于
${auction.highestBid.amount}
修补程序请求主体如下所示:enter image description here创建请求如下所示:enter image description here
//placeBid.js
const AWS = require('aws-sdk');
const createError = require('http-errors');
const {getAuctionById} = require('./getAuction');
const dynamodb = new AWS.DynamoDB.DocumentClient();
async function placeBid(req) {
const { id } = req.pathParameters;
const { amount } = JSON.parse(req.body);
const auction = getAuctionById(id);
if(amount <= auction.highestBid.amount)
throw new createError.Forbidden(`Your Bid Must Be Higher than ${auction.highestBid.amount}`);
const params = {
TableName: 'AuctionsTable',
Key : {id},
UpdateExpression : 'set highestBid.amount = :amount',
ExpressionAttributeValues: {
':amount' : amount
},
ReturnValues : 'ALL_NEW'
}
let updatedAuction;
try {
const result = await dynamodb.update(params).promise();
updatedAuction = result.Attributes;
} catch (error) {
console.error(error);
throw new createError.InternalServerError(error);
}
return{
statusCode : 200,
body : JSON.stringify(updatedAuction)
}
}
module.exports.handler = placeBid;
//getAuction.js
const AWS = require('aws-sdk');
const createError = require('http-errors');
const dynamodb = new AWS.DynamoDB.DocumentClient();
module.exports.getAuctionById = async(id) => {
let auction;
try {
const result = await dynamodb.get({
TableName : 'AuctionsTable',
Key : {id}
}).promise()
auction = result.Item;
} catch (error) {
console.error(error);
throw new createError.InternalServerError(error);
}
if(!auction){
throw new createError.NotFound(`Auction with ID ${id} not found`);
}
return auction;
}
async function getAuction(req) {
const { id } = req.pathParameters;
const auction = await getAuctionById(id);
return{
statusCode : 200,
body : JSON.stringify(auction)
}
}
module.exports.handler = getAuction
3条答案
按热度按时间jhiyze9q1#
你抛出了一个错误而没有捕捉到它
throw new createError.Forbidden(
Your Bid Must Be Higher than ${auction.highestBid.amount});
,所以你的Lambda崩溃并返回500个错误,这是预期的行为。只需返回有效响应即可
x6492ojm2#
如果您想查看使用AWS SDK for JavaScript(v3)编写REST API的示例,该示例可以调用AWS服务并返回数据,请参阅AWS代码目录中的此示例。成功构建REST API后,您可以使用Postman发送请求并查看响应。
此示例执行以下任务:
https://docs.aws.amazon.com/code-library/latest/ug/aurora_example_cross_RDSDataTracker_section.html
jexiocij3#
getAuctionById
是async
。它会传回Promise
。您必须先await
才能使用它的值: