使用AWS SDK V3实现DynamoDB分页API时遇类型错误
问题原因及修复方案
核心问题
- URL拼接错误:直接把
LastEvaluatedKey(对象类型)拼到URL里,JS会自动将其转为[object Object];就算前端手动传了字符串形式的{ MCNo: { N: '456' } },这也只是非标准JSON字符串,不是可直接使用的JS对象。 - ExclusiveStartKey格式错误:给
ExclusiveStartKey传了{ pageKey: ... }的嵌套结构,但DynamoDB要求该参数必须和表的主键结构完全一致(比如你的表主键是MCNo数字类型,就直接传{ MCNo: { N: '456' } },不能嵌套额外层级)。 - 字符串未解析为对象:前端传过来的
lastEvaluatedKey是URL中的字符串,未解析成JS对象就传给DynamoDB,导致SDK无法识别格式,触发报错。
修复后的代码
const page = parseInt(req.query.page, 10) || 1; const pageSize = 10; let startKey; if (page !== 1 && req.query.lastEvaluatedKey) { try { // 先解码URL编码,再解析为JS对象 startKey = JSON.parse(decodeURIComponent(req.query.lastEvaluatedKey)); } catch (err) { console.error('无效的lastEvaluatedKey:', err); return res.status(400).json({ error: '分页参数格式错误' }); } } const scanParams = { TableName: 'carrier', ExclusiveStartKey: startKey, // 直接传解析后的主键对象,无需嵌套 Limit: pageSize, }; const scanCommand = new ScanCommand(scanParams); const result = await dbV3.send(scanCommand); const items = result.Items; let nextPage = null; if (result.LastEvaluatedKey) { // 将对象转为标准JSON字符串并编码,避免URL特殊字符问题 const encodedKey = encodeURIComponent(JSON.stringify(result.LastEvaluatedKey)); nextPage = `${req.baseUrl}?page=${page + 1}&lastEvaluatedKey=${encodedKey}`; } const response = { data: items, nextPage, }; res.json(response); } catch (error) { console.error('请求错误:', error); res.status(500).json({ error: '服务器内部错误' }); }
关键修改点
- 生成
nextPage时,用JSON.stringify把LastEvaluatedKey转为标准JSON字符串,再通过encodeURIComponent处理URL编码,避免特殊字符导致的解析异常。 - 接收参数时,先解码URL编码,再用
JSON.parse把字符串转成JS对象,同时增加try-catch捕获非法输入,提前返回错误。 - 移除
startKey的pageKey嵌套,直接将解析后的主键对象传给ExclusiveStartKey,匹配DynamoDB的参数要求。
内容的提问来源于stack exchange,提问作者sharans singh
相关产品推荐
相关产品推荐

