Express中的app.use与app.get的区别

app.use

app.use的作用是将一个中间件绑定到应用中,参数path是一个路径前缀,用于限定中间件的作用范围,所有以该前缀开始的请求路径均是中间件的作用范围,不考虑http的请求方法,例如:
如果path 设置为’/’,则
- GET /
- PUT /foo
- POST /foo/bar
均是中间件的作用范围。

app.get

app.get是express中应用路由的一部分,用于匹配并处理一个特定的请求,且请求方法必须是GET。

app.use('/',function(req, res,next) {
    res.send('Hello');
    next();
});

等同于:

app.all(/^\/.*/, function (req, res) {
    res.send('Hello');
});

Demo

app.use('/', function(req, res, next) {
    res.write(' root middleware');
    next();
});

app.use('/user', function(req, res, next) {
    res.write(' user middleware');
    next();
});

app.get('/', function(req, res) {
    res.end(' /');
});

app.get('/user', function(req, res) {
    res.end(' user');
});

上述代码中,如果请求http://localhost:3000对应的输出为

root middleware /

请求http://localhost:3000/user对应的输出为

 root middleware user middleware user

https://stackoverflow.com/questions/15601703/difference-between-app-use-and-app-get-in-express-js

  • 1
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值