博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
express中间件_创建自己的Express.js中间件
阅读量:2512 次
发布时间:2019-05-11

本文共 5998 字,大约阅读时间需要 19 分钟。

express中间件

Have you found yourself repeating the same code at the beginning of an Express.js route handler? Perhaps you want to log the path for each incoming request to your application or prevent a user from performing a certain operation. These are prime examples where a custom Express.js middleware would do the trick!

您是否发现自己在Express.js路由处理程序的开头重复了相同的代码? 也许您想记录到应用程序的每个传入请求的路径,或者阻止用户执行某些操作。 这些是定制Express.js中间件可以解决问题的主要示例!

Middleware in Express.js are a powerful, elegant way of handling common functionality in you applications. A couple of popular middleware that you’ve likely already used are (used for parsing a JSON request body) and (enables CORS support for your application). These packages provide huge value and are incredibly easy to configure, largely in part due to the beauty of Express.js’s middleware system.

Express.js中的中间件是一种处理应用程序中常见功能的强大,优雅的方法。 您可能已经使用过的两个流行的中间件是 (用于解析JSON请求正文)和 (为应用程序启用CORS支持)。 这些软件包提供了巨大的价值,并且易于配置,这在很大程度上是由于Express.js中间件系统的优美之处。

入门 (Getting Started)

You’ll need to have Node.js installed first, of course. You can do that . You will also need to have an Express.js application set up. You can to get yours set up.

当然,您需要首先安装Node.js。 你可以在做。 您还需要设置一个Express.js应用程序。 您可以进行设置。

Express中间件剖析 (Anatomy of an Express Middleware)

Express.js middleware are functions that have the following signature:

Express.js中间件是具有以下签名的函数:

function myCustomMiddleware(req, res, next) {  // custom middleware here...}

The req parameter here is an Express.js request object (learn more about the Express.js request object ). The res parameter is an Express.js response object (learn more about the Express.js response object ). Lastly, the next parameter is a function that tells Express.js to continue on to the next middleware you have configured for your application.

req这里参数是一个Express.js请求对象(了解更多关于Express.js请求对象 )。 res参数是Express.js响应对象( 了解有关Express.js响应对象的更多信息)。 最后, next参数是一个函数,该函数告诉Express.js继续使用为应用程序配置的下一个中间件。

Middleware have the ability to modify the req or res objects, run any code you wish, end the request-response cycle, and call the next middleware in the stack. Due to “chaining” style of the middleware stack in Express.js, where each proceeding middleware is required to call next() before moving on, the order in which the middleware are added is of the utmost importance.

中间件具有修改reqres对象,运行所需的任何代码,结束请求-响应周期以及调用堆栈中的下一个中间件的能力。 由于Express.js中中间件堆栈的“链接”样式,每个前进的中间件都需要在继续之前调用next() ,因此中间件的添加顺序至关重要。

修改req对象 (Modifying the   req   Object)

Suppose you want to identify the currently logged in user on every request. You could write a middleware that would fetch the user (user lookup will depend largely on your authentication method) that would something like so:

假设您要在每个请求中标识当前登录的用户。 您可以编写一个中间件来获取用户(用户查找在很大程度上取决于您的身份验证方法),该中间件如下所示:

middleware/setCurrentUser.js
中间件/setCurrentUser.js
// getUserFromToken would be based on your authentication strategyconst getUserFromToken = require("../getUserFromToken");module.exports = function setCurrentUser(req, res, next) {  // grab authentication token from req header  const token = req.header("authorization");  // look up the user based on the token  const user = getUserFromToken(token).then(user => {    // append the user object the the request object    req.user = user;    // call next middleware in the stack    next();  });};

Once you have your shiny new middleware ready to go, you’ll need to add it to your application. This can be done quite simply by “using” the middleware, like so, which enables the middleware for all routes in your application:

一旦准备好使用闪亮的新中间件,就需要将其添加到应用程序中。 可以很简单地通过“使用”中间件来完成,就像这样,它可以为应用程序中的所有路由启用中间件:

server.js
server.js
const express = require('express');const setCurrentUser = require('./middleware/setCurrentUser.js');const app = express();app.use(setCurrentUser);// ...

修改res对象 (Modifying the   res   Object)

Suppose you want to always set a custom header on your response object. This can easily be achieved via a middleware like so:

假设您想始终在响应对象上设置自定义标头。 可以通过这样的中间件轻松实现:

middleware/addGatorHeader.js
中间件/addGatorHeader.js
module.exports = function addGatorHeader(req, res, next) {  res.setHeader("X-Gator-Policy", "chomp-chomp");  next();};

结束请求/响应周期 (Ending the Request/Response Cycle)

A common use case for a middleware is to validate that the user object has been set on your req object. You’re able to do this check and if the user is not found, terminate the request/response cycle, returning an authorized response. Below is a simple example of this approach:

中间件的常见用例是验证是否已在req对象上设置了user对象。 您可以执行此检查,如果找不到用户,则终止请求/响应周期,并返回授权的响应。 下面是此方法的一个简单示例:

middleware/isLoggedIn.js
中间件/isLoggedIn.js
module.exports = function isLoggedIn(req, res, next) {  if (req.user) {    // user is authenticated    next();  } else {    // return unauthorized    res.send(401, "Unauthorized");  }};

Once you have this middleware implemented, you’ll want to add it to your application’s middleware stack. Ordering is very important here! We will combine our earlier example of setting the user via our setCurrentUser middleware and then apply our new middleware. Additionally, we’ll only require the user be authenticated when using a single route, instead of application-wide.

一旦实现了该中间件,就将其添加到应用程序的中间件堆栈中。 在这里订购非常重要! 我们将结合之前的示例,通过setCurrentUser中间件设置user ,然后应用新的中间件。 此外,我们仅要求在使用单个路由时而非在应用程序范围内对用户进行身份验证。

server.js
server.js
const express = require("express");const setCurrentUser = require("./middleware/setCurrentUser.js");const isLoggedIn = require("./middleware/isLoggedIn.js");const app = express();app.use(setCurrentUser);app.get("/users", isLoggedIn, function(req, res) {  // get users...});

With this example only the /users path will require that the user be authenticated.

在此示例中,仅/users路径将要求对用户进行身份验证。

结论 (Conclusion)

With these simple functions we are able to encapsulate application logic that can be reused and is easier to reason about.

通过这些简单的功能,我们可以封装可重复使用且易于推理的应用程序逻辑。

For further reading on writing custom Express.js middleware see the .

有关编写自定义Express.js中间件的更多信息,请参见 。

翻译自:

express中间件

转载地址:http://alhgb.baihongyu.com/

你可能感兴趣的文章
RecyclerView 源码深入解析——绘制流程、缓存机制、动画等
查看>>
Android 面试题整理总结(一)Java 基础
查看>>
Android 面试题整理总结(二)Java 集合
查看>>
学习笔记_vnpy实战培训day02
查看>>
学习笔记_vnpy实战培训day03
查看>>
VNPY- VnTrader基本使用
查看>>
VNPY - CTA策略模块策略开发
查看>>
VNPY - 事件引擎
查看>>
MongoDB基本语法和操作入门
查看>>
学习笔记_vnpy实战培训day04_作业
查看>>
OCO订单(委托)
查看>>
学习笔记_vnpy实战培训day06
查看>>
回测引擎代码分析流程图
查看>>
Excel 如何制作时间轴
查看>>
matplotlib绘图跳过时间段的处理方案
查看>>
vnpy学习_04回测评价指标的缺陷
查看>>
iOS开发中遇到的问题整理 (一)
查看>>
Linux(SUSE 12)安装jboss4并实现远程访问
查看>>
Neutron在给虚拟机分配网络时,底层是如何实现的?
查看>>
netfilter/iptables全攻略
查看>>