node.js - Chained Routing in ExpressJS with path variables -
i trying develop system of chaining express routes in node.js. idea have url like:
api.foo/<somefooid>/bar/<somebarid>
the root js file have
var express = require('express'); var app = express(); var foo = require('./routes/foo'); app.use('/foo', foo);
then routes/foo.js
be:
var express = require('express'); var router = express.router(); var bar = require('./bar'); app.use('/:fooid/bar', bar);
then url pattern shown above handled routes/bar.js
:
var express = require('express'); var router = express.router(); router.get('/:barid', function(req, res) { ... }
this system correctly routes requests above url pattern route bar
, however, req
object not contain fooid
. wondering if knows way bar
route have access fooid
i datsik said, router.get('api/foo/:fooid/bar/:barid')
if absolutely need keep 2 seperate, can attach value :fooid
req
, attach bar
route.
something like, in foo.js
router.get('/api/foo/:fooid', function (req, res, next) { // build data on request. req.fooid = req.params.fooid; req.test = 'this how add data req'; next(); }); // attach bar router.get('/api/foo/:fooid', require('./bar'));
in bar.js
router.get('/bar/:barid', function (req, res, next) { var fooid = req.fooid; // getting value `req` })
Comments
Post a Comment