V2EX = way to explore
V2EX 是一个关于分享和探索的地方
Sign Up Now
For Existing Member  Sign In
WildCat
V2EX  ›  Node.js

Express 的 URL 路由,如何匹配某个固定 URL 路径下的请求,比如/api

  •  
  •   WildCat · May 27, 2014 via iPhone · 6362 views
    This topic created in 4357 days ago, the information mentioned may be changed or developed.
    最近在做一个json api接口,需要匹配/api下的请求。
    想要的实现是这样的:

    app.path('/api', function(app){
    // 匹配 /api/site_info
    app.get('/site_info', someAction);
    });
    8 replies    2014-05-27 14:07:46 +08:00
    jasya
        1
    jasya  
       May 27, 2014
    req.params
    zoowii
        2
    zoowii  
       May 27, 2014
    没用express
    不过这种东西就算没有,自己封装一层context也可以了吧?
    比如
    var ctx = context(['GET', '/info', ...]);
    app.path('/api', ctx)
    kfll
        3
    kfll  
       May 27, 2014   ❤️ 2
    // http://expressjs.com/4x/api.html#router

    var router = express.Router()
    router.get('/site_info', someAction);
    router.get('/member_info', yetAnotherAction);

    app.get('/api', router);
    heroicYang
        4
    heroicYang  
       May 27, 2014
    @kfll 正解
    不过这是 4.x 的 feature,哈哈~
    luin
        5
    luin  
       May 27, 2014 via iPhone   ❤️ 1
    可以看我写的文章:
    http://zihua.li/2014/05/good-practices-to-structure-an-express-app/

    具体来说可以使用 app.use('/app', subApp);,然后 subApp.get('/site_info' , func)。类似 namespace
    WildCat
        6
    WildCat  
    OP
       May 27, 2014
    @luin 谢谢,我在用4.x,直接用express.Router()啦。
    luin
        7
    luin  
       May 27, 2014 via iPhone
    @WildCat 嗯嗯,在 4.0 用 subApp 也有不少优势,比如 app 间隔离,松耦合啥的
    mytharcher
        8
    mytharcher  
       May 27, 2014
    加上 npm install rainbow 效果更好
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   2559 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 36ms · UTC 12:32 · PVG 20:32 · LAX 05:32 · JFK 08:32
    ♥ Do have faith in what you're doing.