在 Node.js 中的 Express 中添加中间件

node.jsserver side programmingprogramming更新于 2024/8/31 13:21:00

app 中的每个请求都会经过 express 中的多个中间件。如果其中一个中间件返回响应,则结束。如果任何中间件想要将请求传递给下一个中间件,它会在其函数调用结束时使用 next() 函数调用。

Http 请求 -> 中间件 (req, resp, next)-> 中间件 (req, res, next)-> Http 响应 ( res.send() )。

const http = require('http');
const express = require('express');
const app = express();
app.use((req, res,next)=>{
   console.log('first middleware');
});
const server = http.createServer(app);
server.listen(3000);

使用 use 函数添加中间件,如上所示。Use() 函数接收三个参数,基本上是 request、response 和 next() 函数。

use() 函数在服务器创建函数之前添加。现在添加第二个中间件 −

运行应用程序 −

打开浏览器并导航到 localhost:3000

在终端控制台上,我们将看到日志消息 −

在第一个中间件中,我们使用 next() 函数调用将 http 请求传递给调用堆栈中的下一个中间件。中间件通常按照文件中的定义工作。

从中间件发送响应

Express 提供了一个 send() 函数来返回任何类型的响应,例如 html、文本等。我​​们也可以使用旧的写入函数。这里我们不需要设置 header,express 会自动设置。

app.use((req, res,next)=>{
   console.log('second middleware');
   res.send('<h1> Hello Tutorials Point </h1>');
});

Nodemon 将在代码更改时自动重启应用程序 −

默认情况下,express.js 中的内容类型为 text/html。我们可以通过使用 response.setHeader() 函数覆盖默认标头值。

如果我们在第一个中间件中删除 next() 函数调用 −

const http = require('http');
const express = require('express');
const app = express();
app.use((req, res,next)=>{
   console.log('第一个中间件');
   //next();
   res.send('<h1> 第一个中间件:Hello Tutorials Point </h1>');
});
app.use((req, res,next)=>{
   console.log('第二个中间件');
   res.send('<h1> 第二个中间件:Hello Tutorials Point </h1>');
});
const server = http.createServer(app);
server.listen(3000);

请注意,我们在第一个中间件中注释了 next() 函数调用

因此我们的 http 请求不会到达第二个中间件,我们只能看到来自第一个中间件的响应。


相关文章