app.use()方法

参考:http://blog.csdn.net/leftfist/article/details/41811021
这里说的app,是指express对象

var express = require(‘express’);

var app = express();

其中,app.use是express“调用中间件的方法”。所谓“中间件(middleware),就是处理HTTP请求的函数,用来完成各种特定的任务,比如检查用户是否登录、分析数据、以及其他在需要最终将数据发送给用户之前完成的任务。”。这是阮一峰文章的原话。

简而言之,app.use() 里面使用的参数,主要是函数。但这个使用,并不是函数调用,而是使能的意思。当用户在浏览器发出请求的时候,这部分函数才会启用,进行过滤、处理。

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

app.use("/about",function(req,res){
    console.log("关于");
    res.send("wroted by leftfist");
});

app.use(function(req,res,next){
    console.log("步骤一");
    res.writeHead(200, { "Content-Type": "text/plain" });
    next();
});
app.use(function(req,res){
    console.log("步骤二");
    res.end("Hello World!");
});

var server = app.listen(3000,function(){
    console.log("http server is ready on 3000")
})

执行结果:
打印log分别是:
http server is ready on 3000
浏览器请求http://localhost:3000/之后显示:
步骤一
步骤二

如果换成:

**var express = require('express');
var app = express();

app.use("/about",function(req,res){
    console.log("关于");
    res.send("wroted by leftfist");
});
app.use(function(req,res){
    console.log("步骤二");
    res.end("Hello World!");
});

app.use(function(req,res,next){
    console.log("步骤一");
    res.writeHead(200, { "Content-Type": "text/plain" });
    next();
});

var server = app.listen(3000,function(){
    console.log("http server is ready on 3000")
})

浏览器请求http://localhost:3000/则log会显示:
http server is ready on 3000
步骤二
因为

app.use(function(req,res){
    console.log("步骤二");
    res.end("Hello World!");
});

有res.end()

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值