快速路线(可选参数)

时间:2014-11-30 22:02:15

标签: regex express parameters routes

我在上班途中遇到了问题。我的路线组织基于:Organizing your app routes with the Express 4 Router

以下是app.js

var express = require('express');
var router = express.Router();

express.use('/object-settings', require("./route/object-settings");
express.use('/object-settings-edit', require("./route/object-settings-edit");

现在文件对象设置

var express = require('express');
var router = express.Router();

router.get('/', function (req, res) {
    // Send home page of this section
});

module.exports = router;

object-settings-edit (请阅读评论,此处描述的问题):

var express = require('express');
var router = express.Router();

router.get('/:id', function (req, res) {
    // Return page for editing object having the ID parameters
});

router.get('/getPageData', function (req, res) {

    // If I'm calling one of those route : 
    //     - /object-edit/getPageData
    //     - /object-edit/getPageData?id=4
    // this route will never be reached ! 
    // This is the preceding one that catch the request. I think I'm understand why, because 
    // any parameters (including the name getPageData) will be catch by the :ìd ? 
  
    // How can I avoid that ? Forcing the id parameter to be a NUMBER only using regex ? 
    // Or maybe there a better way to do it ?
  
    // Return JSon page data 
    var objectID = req.param("id")
    var databaseObject = database.find(objectID);
    res.json(databaseObject);
 
});

module.exports = router;

祝你好运

1 个答案:

答案 0 :(得分:0)

express.Router()每次都会创建一个新的路由器;它未通过express.Router()电话共享。这样做不会像你期望的那样工作:

var router = express.Router();
app.use('/object-settings', router);
router = express.Router();
router.get('/:id', cb);

相反,只需:

var router = express.Router();
// Can be done in either order
router.get('/:id', cb);
app.use('/object-settings', router);

确保引用相同的路由器对象。