app.js file code :
app.post('/update/name', function(req, res){
console.log('Request came : ', req) // I printed the whole request no body came
}
lambda.js (this is the handler function)
'use strict'
const awsServerlessExpress = require('aws-serverless-express')
const app = require('./app')
const binaryMimeTypes = [
'application/javascript',
'application/json',
'application/octet-stream',
'application/xml',
'font/eot',
'font/opentype',
'font/otf',
'image/jpeg',
'image/png',
'image/svg+xml',
'text/comma-separated-values',
'text/css',
'text/html',
'text/javascript',
'text/plain',
'text/text',
'text/xml'
]
const server = awsServerlessExpress.createServer(app, null,
binaryMimeTypes)
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.
}
aws-serverless-express (built in node module) code :
consider this link for the code :
https://github.com/awslabs/aws-serverless-express/blob/master/index.js
In the aws-serverless-code, I commented this line : https://github.com/awslabs/aws-serverless-express/blob/master/index.js#L36 then I was able to get the body in headers['x-apigateway-event'] that I was reading in app.js, but this is not the correct way as I am touching the modules and when I commit the code in github without node modules, then if another member of my team will pull the code, then he will again not get the body.
I had the same problem. I was trying to invoke my express app endpoint as a Lambda function using aws-serverless-express. All the code was fine, but when I invoked the function with sam local invoke MyFunction -e event.json
, I would get an empty req.body
. Eventually, thanks to https://github.com/awslabs/aws-serverless-express/issues/92 , I realized that the event file headers was missing Content-Type
and did not accept application-json
. Adding both to headers
solved the problem.
"headers": {
"Accept": "application/hal+json,text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8",
"Content-Type": "application/json;charset=UTF-8"
}
I had used sam local generate-event api
to generate the event file.
I tried out the AWS CodeStar template for Web Service with Express.js with Lambda and got the same problem. After some hours of googling and reading the above github thread. I just did the following:
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());
That should do it
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.