app.js文件代码:
app.post('/update/name', function(req, res){
console.log('Request came : ', req) // I printed the whole request no body came
}
lambda.js(这是处理函数)
'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(内置节点模块)代码:
consider this link for the code :
https://github.com/awslabs/aws-serverless-express/blob/master/index.js
在aws-serverless代码中,我评论了这一行:https://github.com/awslabs/aws-serverless-express/blob/master/index.js#L36然后我能够在app.js中读取的标题['x-apigateway-event']中获取正文,但是这不是正确的方式,因为我触摸模块,当我在没有节点模块的github中提交代码时,如果我的团队中的另一个成员将提取代码,那么他将再次无法获取正文。
答案 0 :(得分:0)
我有同样的问题。我试图使用aws-serverless-express将我的express应用程序端点作为Lambda函数调用。所有代码都很好,但是当我用sam local invoke MyFunction -e event.json
调用函数时,我会得到一个空的req.body
。最终,由于有了https://github.com/awslabs/aws-serverless-express/issues/92,我意识到事件文件头丢失了Content-Type
并且不接受application-json
。将两者都添加到headers
就解决了这个问题。
"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"
}
我曾经使用sam local generate-event api
来生成事件文件。
答案 1 :(得分:0)
我使用带有Lambda的Express.js尝试了Web Service的AWS CodeStar模板,并遇到了同样的问题。经过几个小时的谷歌搜索和阅读上述github线程。我只是做了以下事情:
安装正文解析器:
$ npm install body-parser --save
然后更新app.js
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(awsServerlessExpressMiddleware.eventContext());
应该这样做