Reputation: 2861
I am trying to test CRUD functionality on a aws lambda function using the Serverless Framework.
Here is the command I am running:
sudo serverless invoke local -f createArticle -p articles/event.json
When I try to create a record an error is thrown. Here is the error in the console:
Syntax Error -------------------------------------------
Unexpected token u in JSON at position 0
For debugging logs, run again after setting the "SLS_DEBUG=*" environment variable.
Get Support --------------------------------------------
Docs: docs.serverless.com
Bugs: github.com/serverless/serverless/issues
Forums: forum.serverless.com
Chat: gitter.im/serverless/serverless
Your Environment Information -----------------------------
OS: darwin
Node Version: 6.10.3
Serverless Version: 1.13.1
Now I have linted my javascript and validated my event.json file.
Here is my javascript:
'use strict';
const AWS = require('aws-sdk');
const dynamo = new AWS.DynamoDB.DocumentClient();
const uuid = require('uuid');
module.exports.handler = (event, context, callback) => {
const data = JSON.parse(event.body);
if (data.text && typeof data.text !== 'string') {
console.log('Validation Failed');
callback(new Error('Body did not contain a text property.'));
return;
}
const params = {
TableName: 'BlogTable',
Item: {
article_id: "1",
text: data.text
}
};
const putCallback = (error, result) => {
if (error) {
console.log(error);
callback(new Error('Could not save record.'));
return;
}
//console.log(result);
const response = {
statusCode: 200,
body: JSON.stringify(result.Item)
};
callback(null, response);
}
dynamo.put(params, putCallback);
};
Here is my event.json
file:
{"text":"Hello World"}
Why is the error getting thrown? And how do I set that environmental variable I tried in my serverless.yml
file but I did not get any output.
Upvotes: 0
Views: 1361
Reputation: 484
If you use the "Lambda proxy" integration, you need to use a specific format for http://
events that directly invoke your Lambda functions (e.g. if you use serverless invoke
from the CLI, and not the AWS API Gateway Management Console, where you can invoke the Lambda function through your API using the "Test" button).
With a Lambda proxy, in this example, you need to create a json file with a "body" property and stringify the value, like this:
{
"body": "{\"text\":\"hello\"}"
}
The reason is: "With the Lambda proxy integration, API Gateway maps the entire client request to the input event parameter of the back-end Lambda function" http://docs.aws.amazon.com/apigateway/latest/developerguide/api-gateway-set-up-simple-proxy.html#api-gateway-simple-proxy-for-lambda-input-format
Upvotes: 1
Reputation: 2861
In my event.json files I had to put my json like this:
{"body": "{\"text\": \"Hello World\"}"
Upvotes: 0