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执行

     

  • 相关阅读:
    树莓派摄像头直播程序,非常希望有贡献者一起玩
    Ansible 操作windows
    Python实现自平衡二叉树AVL
    Python非递归遍历多叉树
    Python 非递归遍历图
    使用ffmpeg进行网络直播
    Python安装mysqldb
    运维工程师速成
    科幻小说《霜与火》 by 雷·布雷德伯里
    jvm 内存调整
  • 原文地址:https://www.cnblogs.com/bsn-huang/p/3916951.html
Copyright © 2011-2022 走看看