简体   繁体   中英

Access to aws-lambda context when running nodejs + expressjs

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:

  1. Is there a way to access the AWS-Lambda "context" with this structure?
  2. If not, what would be the best "pattern" to make it available?

Any input appreciated.

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;

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM