zoukankan      html  css  js  c++  java
  • learning express step(九)

    router-level middleware works in the same way as application-level middleware, except it is bound to an instance of  express.Router().

    code: 

    var express = require('express');
    var app = express();
    var router = express.Router();
    
    // a middleware function with no mount path. This code is executed for every request to the router
    router.use(function (req, res, next) {
        console.log('Time:', Date.now());
        next()
    });
    
    // a middleware sub-stack shows request info for any type of HTTP request to the /user/:id path
    router.use('/user/:id', function (req, res, next) {
        console.log('Request URL:', req.originalUrl);
        next()
    }, function (req, res, next) {
        console.log('Request Type:', req.method);
        next()
    });
    
    // a middleware sub-stack that handles GET requests to the /user/:id path
    router.get('/user/:id', function (req, res, next) {
        // if the user ID is 0, skip to the next router
        if (req.params.id === '0') next('route');
        // otherwise pass control to the next middleware function in this stack
        else next()
    }, function (req, res, next) {
        // render a regular page
        res.send('regular');
    });
    
    // handler for the /user/:id path, which renders a special page
    router.get('/user/:id', function (req, res, next) {
        console.log(req.params.id);
        res.send('special');
    });
    
    app.set('view engine','jade');
    // mount the router on the app
    app.use('/', router);
    
    app.listen(3000);

    result:

  • 相关阅读:
    10:简单密码
    08:字符替换
    07:配对碱基链
    05:输出亲朋字符串
    18:等差数列末项计算
    09:密码翻译
    用最通俗的话说23种设计模式之代理模式
    Android学习之 UI效果
    精确到时分秒的jQuery插件例子
    Eclipse 常用快捷键
  • 原文地址:https://www.cnblogs.com/lianghong881018/p/11014619.html
Copyright © 2011-2022 走看看