Express Route (Optional parameters)

☆樱花仙子☆ 提交于 2021-02-11 15:14:28

问题


I have a problem getting my route to work. I have based the route organisation on : Organizing your app routes with the Express 4 Router

Here is 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");

Now the file object-settings

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

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

module.exports = router;

And the object-settings-edit (Please read the comments, the problem is described here) :

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;

Best regards


回答1:


express.Router() creates a new router each time; it's not shared via the express.Router() call. Doing this won't work as you seem to expect:

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

Instead, just do:

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

Just make sure you are referencing the same router object.



来源:https://stackoverflow.com/questions/27218770/express-route-optional-parameters

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!