问题
I'm, just starting out with AWS-Lambda, AWS-API Gateway and ExpressJs. I'm having trouble finding how the AWS-Lambda "context" is available in my "ExpressJs" application.
I'm using:
- AWS-Lambda
- AWS-API Gateway
- NodeJs v4.3.2
- ExpressJs 4.14.1
- ClaudiaJs 2.7.0
In Aws Lambda I use aws-serverless-express to receive the API-Gateway request and initialize the node application. The following is the structure I have found from different tutorials, etc
lambda.js (Initiated from API-Gateway. Supplying the "context" variable in the call to "app.js")
'use strict'
const awsServerlessExpress = require('aws-serverless-express')
const app = require('./app')
const server = awsServerlessExpress.createServer(app)
exports.handler = (event, context) => awsServerlessExpress.proxy(server, event, context)
The core of my app.js express is:
var express = require('express');
...
var app = express();
...
app.use('/', index);
...
module.exports = app;
My questions:
- Is there a way to access the AWS-Lambda "context" with this structure?
- If not, what would be the best "pattern" to make it available?
Any input appreciated.
回答1:
You need to add middleware included in the aws-serverless-express package which exposes the event
and context
objects. You add it like this:
const awsServerlessExpressMiddleware = require('aws-serverless-express/middleware')
app.use(awsServerlessExpressMiddleware.eventContext())
Once this middleware is configured the event
and context
objects will be added to the request. You access those objects like so:
var event = req.apiGateway.event;
var context = req.apiGateway.context;
来源:https://stackoverflow.com/questions/42436527/access-to-aws-lambda-context-when-running-nodejs-expressjs