Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"Unexpected token u in JSON at position 0"

When I run the endpoint on Postman it works fine and returns the result it posted, but when I use TEST on AWS lambda it returns the error "Unexpected token u in JSON at position 0". I checked the Use Lambda proxy on API gateway inside integration request, would that effect something?

Here is my lambda function

'use strict';

const uuid = require('uuid');
const AWS = require('aws-sdk'); // eslint-disable-line import/no-extraneous-dependencies

const dynamoDb = new AWS.DynamoDB.DocumentClient();

module.exports.create = (event, context, callback) => {
  const timestamp = new Date().getTime();
  const data = JSON.parse(event.body);

  if (typeof data.phoneNumber !== 'string') {
    console.error('Validation Failed');
    callback(null, {
      statusCode: 400,
      headers: { 'Content-Type': 'text/plain' },
      body: 'Couldn\'t create item.',
    });
    return;
  }

  const params = {
    TableName: process.env.DYNAMODB_TABLE,
    Item: {
      id: uuid.v1(),

      phoneNumber: data.phoneNumber,
      sub: data.sub,

      createdAt: timestamp,
      updatedAt: timestamp,
    },
  };

  console.log(params);

  // write the lakeSubscription to the database
  dynamoDb.put(params, (error) => {
    // handle potential errors

    if (error) {
      console.error(error);
      callback(null, {
        statusCode: error.statusCode || 501,
        headers: { 'Content-Type': 'text/plain' },
        body: 'Couldn\'t create in dynamoDb.',
      });
      return;
    }

    // create a response
    const response = {
      statusCode: 200,
      body: JSON.stringify(params.Item),
    };
    callback(null, response);
  });
};

like image 932
Jason Avatar asked Mar 04 '23 10:03

Jason


1 Answers

First of all if you see the JSON that you have provided:

{ "phoneNumber": "+11231231234", "sub": [ { "Name": "Tillery" }, { "Name": "Bob" } ] }

There's no body key. You can just use event instead of event.body. Like

console.log(event);

The input from AWS test event is already JSON Object and you don't need to parse it again.

Please remove JSON.parse and you'll be good.

Thanks!

like image 106
Hassan Murtaza Avatar answered Apr 01 '23 12:04

Hassan Murtaza