请求正文未从 aws-serverless-express 模块进入 app.js 文件



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-code 中,我注释了这一行:https://github.com/awslabs/aws-serverless-express/blob/master/index.js#L36 然后我能够在 app.js 中读取的标头 ['x-apigateway-event'] 中获取正文,但这不是正确的方法,因为我正在触摸模块,当我在没有节点模块的情况下在 github 中提交代码时,那么如果我团队的另一个成员将提取代码, 然后他将再次得不到身体。

我遇到了同样的问题。我尝试使用 aws-serverless-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生成事件文件。

我用Express.js Lambda尝试了用于Web服务的AWS CodeStar模板,并遇到了同样的问题。经过几个小时的谷歌搜索和阅读上面的github线程。我刚刚做了以下操作:

安装正文解析器:

$ npm install body-parser --save

然后更新app.js

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(awsServerlessExpressMiddleware.eventContext());

那应该可以做到

最新更新