Ad
"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);
});
};
Ad
Answer
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!
Ad
source: stackoverflow.com
Related Questions
- → Maximum call stack exceeded when instantiating class inside of a module
- → Browserify api: how to pass advanced option to script
- → Node.js Passing object from server.js to external modules?
- → gulp-rename makes copies, but does not replace
- → requiring RX.js in node.js
- → Remove an ObjectId from an array of objectId
- → Can not connect to Redis
- → React: How to publish page on server using React-starter-kit
- → Express - better pattern for passing data between middleware functions
- → Can't get plotly + node.js to stream data coming through POST requests
- → IsGenerator implementation
- → Async/Await not waiting
- → (Socket.io on nodejs) Updating div with mysql data stops without showing error
Ad