express中间件_创建自己的Express.js中间件

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

入门 (Getting Started)

You’ll need to have Node.js installed first, of course. You can do that here. You will also need to have an Express.js application set up. You can follow along here 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 here). The res parameter is an Express.js response object (learn more about the Express.js response object here). 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 strategy
const 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 official docs.

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

翻译自: https://www.digitalocean.com/community/tutorials/nodejs-creating-your-own-express-middleware

express中间件

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值