AWS-Serverless-Express 如何获取先前的路由

Posted

技术标签:

【中文标题】AWS-Serverless-Express 如何获取先前的路由【英文标题】:AWS-Serverless-Express How To Get Previous Route 【发布时间】:2020-09-14 18:09:29 【问题描述】:

我的前端有一个导出按钮,单击该按钮时,会在我们的 Express 服务器上发送一个 POST 以记录按钮单击。这使用路由 app.post(usagereport) 。我想要做的是捕获用户单击导出时所处的路线。但是,由于发送 POST 请求的代码是它自己的路由,因此它只会在尝试类似req.route 时返回该路由的名称。

我正在使用 API Gateway + Lambda + AWS-Serverless-Express。

我在想我可以在 req.session 中存储req.session.previousRoute 之类的内容,以捕获用户加载的最后一条路由,然后将其返回给访问日志代码。但是,我不确定这种方法是否适用于 Lambda,或者是否有更好的方法来处理它。

这是我的 server.js(精简版)

// create the server and setup routes
const app = express();
const mysql = require("mysql");

// AWS-Serverless-Express https://github.com/awslabs/aws-serverless-express
const awsServerlessExpressMiddleware = require("aws-serverless-express/middleware");
app.use(awsServerlessExpressMiddleware.eventContext());

//Setup paths to database connection pools
const nawfprojectsDB = require("../lib/naWfProjectsDb.js");
const queries = require("./queries.js");
const accessLog = require("../lib/accessLog.js");

//Setup a timestamp for logging
const timestamp = new Date().toString();

// S3 Data Mitigation is needed when a data set exceeds 5 MB in size.
// This is a restriction of Lambda itself (they say 6 MB but want to ensure we dont ever hit the limit)
const s3DataMitigation = require("../lib/s3DataMitigation.js");

let environment = process.env.NODE_ENV;

app.get("/wg_data", (req, res, callback) => 
  const dataSet = "wg_data";
  nawfprojectsDB.query(queries.wg_data, (err, result) => 
    if (err) 
      console.log(err);
    
    s3Data(dataSet, res, callback, result);
    console.log(
      timestamp,
      "Returned " + result.length + " rows from  " + dataSet
    );
  );
  accessLog( dataSet, req );
);

// Usage report everytime export button is clicked
app.post("/usagereport", (req) => 
  const currentPath = dataSet;
  const dataSet = "Data Exported: " + currentPath;
  console.log(timestamp, "Data exported");
  accessLog( dataSet, req );
);


module.exports = app;

accessLog.js

let nawfprojectsDB = require("./naWfProjectsDb.js");
let queries = require("../routes/queries.js");
let environment = process.env.NODE_ENV;

//Insert data into access_logs table when usageLog is called
const accessLog = ( dataSet, req ) => 
  // We only want to log access when in beta, gamma, or prod. Not in development.
  if (environment === "development") 
    console.log("No access log as we are in dev");
   else 
    // req.apiGateway comes from AWS-Serverless-Express - https://github.com/awslabs/aws-serverless-express
    const user = req.apiGateway.event.requestContext.authorizer.principalId;
    let sqlData = [dataSet, user, environment];
    // Run the log_access query using the sqlData above
    nawfprojectsDB.query(queries.log_access, sqlData, (err) => 
      if (err) 
        console.error("MySQL query error: " + err);
      
      console.log("Access log added for: ", user, " at data set: ", dataSet);
    );
  
;

module.exports = accessLog;

【问题讨论】:

【参考方案1】:

解决了我自己的问题。

解决这个问题的方法是使用 express-session。我在每条路线中都设置了req.session.previousRoute。然后我可以在我的usagereport 路由中访问它。

const  v4: uuidv4  = require("uuid");
const express = require("express");
const cookieParser = require("cookie-parser");
const session = require("express-session");
const randomString = uuidv4();
let sessionOptions = 
  cookie: 
    secret: randomString,
    maxAge: 269999999999,
  ,
  saveUninitialized: true,
  resave: true,
;
// create the server and setup routes
const app = express();

// Add express-session Middleware - https://www.npmjs.com/package/express-session
app.use(cookieParser(randomString)); // Need cookieParser to properly parse our random string into the type of value expected by session
app.use(session(sessionOptions));

// AWS-Serverless-Express - https://github.com/awslabs/aws-serverless-express
const awsServerlessExpressMiddleware = require("aws-serverless-express/middleware");
app.use(awsServerlessExpressMiddleware.eventContext());

app.get("/wg_data", (req, res, callback) => 
  const dataSet = "wg_data";
  const action = "Accessed";
  req.session.previousRoute = dataSet; // This is where we set the previousRoute in session
  nawfprojectsDB.query(queries.wg_data, (err, result) => 
    if (err) 
      console.log(err);
    
    s3Data(dataSet, res, callback, result);
    console.log(
      timestamp,
      "Returned " + result.length + " rows from  " + dataSet
    );
  );
  accessLog( dataSet, action, req );
);

// Usage report everytime export button is clicked
app.post("/usagereport", (req) => 
  // Here we grab the previousRoute set in session to see the true place the data was exported from
  const action = "Exported";
  const previousRoute = req.session.previousRoute; // Now when usagereport is triggered, it knows the previous route from the session and uses that here.
  const dataSet = previousRoute;
  console.log(timestamp, "Data exported from ", previousRoute);
  accessLog( dataSet, action, req );
);

【讨论】:

以上是关于AWS-Serverless-Express 如何获取先前的路由的主要内容,如果未能解决你的问题,请参考以下文章

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

Express GraphQL 必须提供查询字符串。

HTTP/2 推送 AWS API Gateway + Lambda

无服务器快递无法检索 pdf 文件(base64 编码)

ByteDance字节跳动张一鸣:如何阅读如何了解自己如何与人沟通沟通如何安排时间如何正确的看待别人意见如何激励自己如何写作如何坚持锻炼身体如何耐心?...

Markdown公式用法大全