You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Node.js+AWS构建REST API出价接口报错求助

问题排查与修复

核心错误点

  1. 异步函数调用未等待结果
    getAuctionById是异步函数,直接赋值给auction得到的是Promise对象而非实际拍卖数据,直接访问auction.highestBid.amount会触发属性读取错误。

  2. 请求体解析逻辑有问题
    Cloudwatch提示的"Cannot read property 'amount' from request body",原因大概率是:

    • API Gateway的Lambda代理集成默认会自动解析JSON请求体,此时req.body已是JSON对象,重复JSON.parse会报错
    • 未处理请求体解析失败的情况,一旦请求体格式错误,直接解构amount会抛出异常
  3. 缺少参数有效性校验
    未检查amount是否存在、是否为有效正数,会导致后续逻辑无意义报错。

修复后的代码

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;
  
  // 兼容请求体已解析/未解析的情况,处理解析错误
  let requestBody;
  try {
    requestBody = typeof req.body === 'string' ? JSON.parse(req.body) : req.body;
  } catch (err) {
    throw new createError.BadRequest('Invalid request body format');
  }

  // 校验出价参数有效性
  const { amount } = requestBody;
  if (!amount || typeof amount !== 'number' || amount <= 0) {
    throw new createError.BadRequest('Valid positive bid amount is required');
  }

  // 等待异步函数返回实际拍卖数据
  const auction = await 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;

额外测试建议

  • Postman请求时确保Content-Type头设为application/json,请求体用标准JSON格式,示例:
    {
      "amount": 150
    }
    
  • 先调用getAuction接口确认目标拍卖项的highestBid.amount值,再发送符合要求的出价请求验证提示逻辑。

内容的提问来源于stack exchange,提问作者Ojaswi Awasthi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.10 20:50:33