nodejs/express学习笔记(1) - app.use()

本文详细介绍了Express.js中中间件的使用方法,包括如何通过app.use加载中间件、路径匹配规则及顺序的重要性,并展示了多种常见中间件的应用实例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

基本描述

app.use([path,] callback [, callback…])
用于加载中间件,或在指定[path]匹配时加载callback中间件。

router 和 express
router 和 express 对象都实现了中间件借口,因此也可以当作callback中间件使用。

// router当作callback中间件
 var router = express.Router();
router.get('/', (req, res, next) => {
  next();
});
app.use(router);

//express应用当作callback中间件
var subApp = express();
subApp.get('/', (req, res, next)=> {
  next();
});
app.use(subApp);

路径的匹配问题
路由将会匹配所有的后续连接有”/”的[path]。例如, app.use(‘/apple’, …) 将会匹配“/apple”, “/apple/images”, “/apple/images/news”,等等。

因此在路径匹配规划时,顺序非常重要。在下面的例子中,如果把”/”放在首位,则后续的其它路径匹配将不会执行。

app.use('/',(req,res)=>{
    res.end('welcome');
});

上面语句中,res.end已经结束了本次会话,因此,当用户请求”/news”时,即使下面的路径匹配,也将无法执行。

app.use('/news',(req,res)=>{
    res.end('news');
});

[path]的默认值是”/”,因此在未指定[path]的情况下,每次对app的请求都会执行callback中间件。例如以下三个例子中,每次用户请求都会输出一个日志:

app.use((req, res, next)=> {
  console.log('Time: %d', Date.now());
  next();
});

app.use('/', (req,res) => {
    console.log('Time: %d', Date.now());
    res.render('index');
});

多个路径匹配的处理
在多个路径匹配的情况下,用next参数将控制权传递到下一个请求中间件处理。下面的例子中,对路径”/news”的访问将顺序由两个中间件处理。

app.use('/news',(req, res, next) => {
    //do something
    console.log('First callback executed.');
    next(); // 转移控制权
});

app.use('/', (req, res) => {
    //do something
    console.log('Second callback executed.');
    res.end();
});

Callback中间件

在没有指定[path]的情况下,默认为所有访问请求均会执行。

//express.static
app.use(express.static(__dirname + '/public'));
app.use('/static', express.static(__dirname + '/public'));

//favicon,添加网站图标
app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));

//logger,日志
app.use(logger('dev'));

//bodyParser,内容解析
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));

//cookieParser,cookie解析
app.use(cookieParser());

Error-handling 中间件

Error-handling 中间件必须包含四个参数,与其它中间件只有3个参数不同的是,只有指定四个参数的中间件才被认可为Error-handling 中间件。

app.use((err, req, res, next) => {
  console.error(err.stack);
  res.status(500).send('Something broke!');
});
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值