nodejsexpress学习笔记(1) - app.use()

    xiaoxiao2021-03-25  57

    基本描述

    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!'); });
    转载请注明原文地址: https://ju.6miu.com/read-37209.html

    最新回复(0)