zoukankan      html  css  js  c++  java
  • Node.js笔记(0003)---Express框架Router模块学习笔记

    这段时间一直有在看Express框架的API,最近刚看到Router,以下是我认为需要注意的地方:

    Router模块中有一个param方法,刚开始看得有点模糊,官网大概是这么描述的:

    Map logic to route parameters.
    

    大概意思就是路由参数的映射逻辑

    这个可能一时半会也不明白其作用,尤其是不知道get和param的执行顺序

    再看看源码里面的介绍:

     Map the given param placeholder `name`(s) to the given callback.
     Parameter mapping is used to provide pre-conditions to routes
     which use normalized placeholders
    

    这就清晰多了,翻译过来就是说:

    在所给的参数和回调函数之间做一个映射,作为使用标准化占位符的路由的前提条件。

    下面给出一段具体代码:

    var express = require('express');
    var app = express();
    var router = express.Router();
    
    router.count = 0;
    router.get('/users/:user', function(req, res, next) {
        router.count ++;
        console.log(router.count);
    });
    router.param('user', function(req, res, next, id) {
        router.count ++;
        res.send({count: router.count});
        next();
    });
    
    app.use(router);
    app.listen(3000);
    

    命令行下输入

    node xxx.js

    浏览器访问

    http://localhost:3000/users/bsn

    这时候命令行会输出2,而浏览器会输出

    {
    count: 1
    }

    因此,param会先于get执行

     

  • 相关阅读:
    中南大学ACM12月月赛第二场热身赛解题报告
    中南大学ACM12月月赛第二场热身赛在本周日(2011年11月20日)举行
    IPv4 and IPv6
    Java and IPV6
    IPv6 and Java
    poj3385
    poj3390
    poj3226
    poj3767
    poj3497
  • 原文地址:https://www.cnblogs.com/bsn-huang/p/3916951.html
Copyright © 2011-2022 走看看