Access to aws-lambda context when running nodejs + expressjs

南笙酒味 提交于 2021-02-18 22:49:45

问题


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.


回答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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!