在 express.js 中处理不同的路由
为了处理不同的路由,使用了 use() 函数。use() 函数有多个重载版本,其中一个版本将 url 路径作为参数。根据 url 路径,将筛选请求以获取各自的中间件。
const http = require('http');
const express = require('express');
const app = express();
app.use('/', (req, res,next)=>{
console.log('first middleware');
res.send('<h1> first midleware:
Hello Tutorials Point </h1>');
});
const server = http.createServer(app);
server.listen(3000);在上面的示例中,我们使用 ‘/’ 作为 url 路径,这是一个默认值。
现在,由于每个路由都以 ‘/’ 开始,因此上面的中间件将执行每个 http 请求。它适用于 ‘/’ 和 ‘/username’。
为了避免上述问题,在使用默认中间件之前,我们必须先使用特定于路径的中间件。
const http = require('http');
const express = require('express');
const app = express();
app.use('/username', (req, res,next)=>{
res.send('<h1> My username </h1>');
});
app.use('/', (req, res,next)=>{
console.log('first middleware');
res.send('<h1> first midleware: Hello Tutorials Point </h1>');
});
const server = http.createServer(app);
server.listen(3000);现在,我们首先使用 ‘/username’ 路径中间件,由于我们在其中没有使用 next(),因此它不会将 http 请求传递到下一个中间件。
因此,我们看到不同 url 的浏览器输出如下 −
localhost:3000

对于 localhost:3000/username

如果对所有内容都需要执行任何预处理,那么使用默认中间件 url 路径 ‘/’ 将很有用。我们只需在其中使用 next() 即可将处理后的请求传递到下一个中间件。
const http = require('http');
const express = require('express');
const app = express();
app.use('/', (req, res,next)=>{
console.log('log request info', req);
next();
});
app.use('/username', (req, res,next)=>{
res.send('<h1> My username </h1>');
});
app.use('/', (req, res,next)=>{
console.log('first middleware');
res.send('<h1> first midleware: Hello Tutorials Point </h1>');
});
const server = http.createServer(app);
server.listen(3000);
广告
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP