javascript - 位置 6 AWS Lambda 的 JSON 中的意外意外令牌 t
问题描述
我正在编写一个简单的lambda
函数,它使用发布请求将一些数据插入到DynamoDB
但是在部署 lambda 函数之后502 Bad Gateway
,当我尝试测试该函数时,我不断收到一个邮递员。
我尝试AWS
通过API Gateway
返回以下堆栈跟踪进行调试。
Endpoint response body before transformations: {"errorType":"SyntaxError","errorMessage":"Unexpected token t in JSON at position 6","trace":["SyntaxError: Unexpected token t in JSON at position 6"," at JSON.parse (<anonymous>)"," at Runtime.module.exports.createPost [as handler] (/var/task/handler.js:16:24)"," at Runtime.handleOnce (/var/runtime/Runtime.js:66:25)"]}
但是,我不确定 JSON 到底在哪里有语法错误。
这是示例请求
curl --location --request POST 'https:localhosttest:3000/dev/post' \
--header 'Content-Type: application/json' \
--data-raw '{
"title": "POST One TEST",
"body": "This is the first post"
}'
这是我的代码
"use strict";
const AWS = require("aws-sdk");
const db = new AWS.DynamoDB.DocumentClient({ apiVersion: "2012-08-10" });
const { v4: uuidv4 } = require("uuid");
const postsTable = process.env.POSTS_TABLE;
const response = (statusCode, message) => {
return {
statusCode,
body: JSON.stringify(message),
};
};
module.exports.createPost = (event, context, callback) => {
const reqBody = JSON.parse(event.body);
const post = {
id: uuidv4,
createdAt: new Date().toISOString(),
userId: 1,
title: reqBody.title,
body: reqBody.body
};
return db
.put({
TableName: postsTable,
Item: post
})
.promise()
.then(() => {
callback(null, response(201, post));
})
.catch((err) => response(null, response(err.statusCode, err)));
};
当我 看到以下内容console.log
时:event.body
{
"title": "POST One TEST",
"body": "This is the first post"
}
我可以看到的堆栈跟踪cloudwatch
是
ERROR Invoke Error
{
"errorType": "SyntaxError",
"errorMessage": "Unexpected token t in JSON at position 6",
"stack": [
"SyntaxError: Unexpected token t in JSON at position 6",
" at JSON.parse (<anonymous>)",
" at Runtime.module.exports.createPost [as handler] (/var/task/handler.js:17:24)",
" at Runtime.handleOnce (/var/runtime/Runtime.js:66:25)"
]
}
解决方案
event.body 已经是对象类型,因此您可能会遇到错误。
或控制台事件类型,正文以正确调试。
您可以执行以下操作:
const reqBody = typeof event.body === 'string' ? JSON.parse(event.body) : event.body;
推荐阅读
- python - 描述性文件名
- docker - 使用 Docker 的 Go SDK 时输出中的杂散字符
- java - 如何将计数器结果编号保存到文本视图中?
- azure-devops - YAML 管道定义,它从管道变量中检索变量值
- svg - 如何为具有不同数量控制点的 2 条 SVG 路径设置动画?
- android - 我想让按钮可拖动,并且它会颤动一些按钮
- javascript - 如何使用 useEffect 钩子渲染加载组件?
- grpc - NoSuchMethodError gRPC
- installation - 使用 MSYS2 安装 gfortran
- python - BigQuery Storage API 并行运行流