简体   繁体   中英

Getting an error while parsing event body to json in aws console

I'm using lambda with aws and a serverless framework. When I test this with serverless offline it works completely fine but when I deploy it I keep getting a message: internal server error and when I log in to aws console, the Error says

  "errorType": "SyntaxError",
  "errorMessage": "Unexpected token p in JSON at position 0",
  "trace": [
    "SyntaxError: Unexpected token p in JSON at position 0",
    "    at JSON.parse (<anonymous>)",
    "    at module.exports.createPost (/var/task/handlers/post.js:17:12)",
    "    at Runtime.handler (/var/task/serverless_sdk/index.js:9:89602)",
    "    at Runtime.handleOnce (/var/runtime/Runtime.js:66:25)"
  ]

This is my handler

module.exports.createPost = async event => {
  const data = JSON.parse(event.body);
  const post = {
    id: uuid.v4(),
    createdAt: new Date().toISOString(),
    userId: 1,
    title: data.title,
    body: data.body
  };
  const params = {
    TableName: postsTable,
    Item: post
  };
  db.putItem(params, (err, data) => {
    if (err) {
      return response(err.statusCode, err);
    } else {
      return response(200, post);
    }
  });
};

I'm testing this with

{
  "title": "post title",
  "body": "post body"
}

I guess body is already a json so if you do json.parse again, it will throw this error. If you remove the json.parse , it should be ok.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM