首页 > 解决方案 > 位置 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)"
    ]
}

标签: javascriptnode.jsaws-lambdaamazon-dynamodb

解决方案


event.body 已经是对象类型,因此您可能会遇到错误。

或控制台事件类型,正文以正确调试。

您可以执行以下操作:

const reqBody = typeof event.body === 'string' ? JSON.parse(event.body) : event.body;

推荐阅读