问题
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