@brettstack
Code Snippet:
//app.js
app.post('/user', function(req, res){
console.log('Request came : ', req.body) // print the request empty body
}
//lambda.js
'use strict'
const awsServerlessExpress = require('aws-serverless-express')
const app = require('./app')
const server = awsServerlessExpress.createServer(app)
exports.handler = (event, context) => {
console.log('body came from api gateway', event.body) // here we can see the body in cloudwatch logs
awsServerlessExpress.proxy(server, event, context) // but when this method makes request to our app.js file where the request goes, no body comes there.
}
What's the request's content-type header? It needs to be 'application/json' for Express to accept json.
It working fine using Postman. Whenever I testing using Amazon API Gateway it returns empty body.
Below is Request header while calling API via Amazon API Gateway:
Accept:application/hal+json
Content-Type:application/json;charset=UTF-8
Problem seems to be amazon api gateway that it sends body as string to Lambda function!!!
@brettstack is there a way to make it work with the content-type of "application/x-www-form-urlencoded"?
Yes, but it's not as easy as we'd like just yet. You will need to configure a resource (path/route) and method (likely POST) to override the greedy path resource for the route you want this content type in (match your Express route) and add a mapping template for that resource+method to do the transformation for you. See this SO https://stackoverflow.com/questions/32057053/how-to-pass-a-params-from-post-to-aws-lambda-from-amazon-api-gateway
Remember to use bodyParser.json() or bodyParser.urlencoded({ extended: false }) as express middleware to make sure the body is available in the req object.
I tried out the AWS CodeStar template for Web Service with Express.js with Lambda.
Just to complement the above answer and save some time to others:
Remember to install body parser
$ npm install body-parser --save
Then update app.js
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(awsServerlessExpressMiddleware.eventContext());
I added the bodyparser but the body is still missing from inside awsServerlessExpress.proxy(server, event, context), anyone have any suggestions?
set headers to have Content-Type:application/json
Most helpful comment
What's the request's
content-typeheader? It needs to be 'application/json' for Express to accept json.