您当前的位置:首页 > 计算机 > 编程开发 > JavaScript

Express Middleware 中间件介绍和使用

时间:12-14来源:作者:点击数:

当 Express 服务器接收到 HTTP 请求时,它会执行一系列 中间件 函数。 中间件函数负责 处理请求 和 制作响应 。

您通常会看到中间件定义为具有 3 个参数的函数: reqres, 和 next,这条规则最大的例外是 错误处理中间件 。

要向您的 Express 应用程序添加中间件功能,请调用 app.use()

const app = require('express')();

app.use((req, res, next) => {
  req; // The request
  res; // The response
  next; // A function that you must call to trigger the next middleware
});

在引擎盖下,当你调用时 app.use(),Express 将您的函数添加到 其内部中间件 堆栈 。 Express 按添加顺序执行中间件,因此如果您调用 app.use(fn1); app.use(fn2);,Express 会执行 fn1 、fn2

中间件与路由处理程序

假设您有一个简单的 Express 服务器,它使用字符串 Hello, World 响应 GET 请求,如下所示。

const app = require('express')();

app.get('/', function routeHandler(req, res) {
  res.send('Hello, World');
});

在 Express 中,路由处理程序只是一种从不调用的特殊类型的中间件 next(),你也可以编写一个做同样事情的中间件。

app.use(function(req, res, next) {
  // Do nothing if the request isn't `GET /`
  if (req.method !== 'GET' || req.url !== '/') {
    return next();
  }
  res.send('Hello, World');
});

路由

这 app.use() 函数 有 2 个参数:一个可选的 path,和一个中间件函数 callback。如果第一个参数为 app.use(),Express 只会执行相应的中间件函数 URL 匹配。

// Express will only call `middleware()` if `req.url` is equal to '/'
app.use('/', function middleware(req, res, next) {
  // Do nothing if the request isn't a 'GET' request
  if (req.method !== 'GET') {
    return next();
  }
  res.send('Hello, World');
});

next() 功能

如果您有多个中间件功能,则需要确保您的中间件调用 next() 或发送回复。 如果您编写 Express 中间件,这是您的责任。 如果你的中间件没有调用 Express 不会抛出错误 next(),它会 简单地挂起 。

// If you open this page in Chrome, it will just keep loading forever.
app.use('/', function middleware(req, res, next) {
  console.log('Test');
});

一般来说,最好的做法是调用 next() 除非您明确不希望中间件堆栈的其余部分运行。调用 next() 如果没有更多的中间件就很好了。

// It is OK to call `next()` even if there's no more middleware.
app.use((req, res, next) => {
  res.send('Hello, World');
  next();
});

如果你打电话 next() 带有参数,Express 会将该参数视为错误并触发 错误处理中间件 。 下面的中间件将导致 Express 响应 HTTP 500 和堆栈跟踪。

app.use((req, res, next) => {
  next(new Error('Fail!'));
});

如果您在 Chrome 中打开上述中间件,您会看到如下内容:

HTTP 响应错误示例
方便获取更多学习、工作、生活信息请关注本站微信公众号城东书院 微信服务号城东书院 微信订阅号
推荐内容
相关内容
栏目更新
栏目热门
本栏推荐