zoukankan      html  css  js  c++  java
  • Node.js -- Router模块中有一个param方法

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

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

    1
    Map logic to route parameters.

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

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

    再看看源码里面的介绍:

    1
    2
    3
    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

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

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

    下面给出一段具体代码:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    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执行

  • 相关阅读:
    [sql查询] 重复数据只取一条
    SSIS,参数坑
    数据仓库之建立多维数据库
    数据仓库之SSIS开发
    开发规范
    页面以base64输出图片
    内嵌iframe
    T-Sql编程基础
    MVC3.0----整理之一
    原生JS 表单提交验证器
  • 原文地址:https://www.cnblogs.com/chris-oil/p/4985542.html
Copyright © 2011-2022 走看看