2016-01-26 68 views
0

所以我一直在絞盡腦汁想了很久,現在試圖弄清楚這一點,我仍然有問題。Express.js,req.params不被稱爲

所以我這樣定義一個路線:

var home = require('./routes/home'); 
var app = express(); 

app.use('/home/:client', home); 

而且我home.js代碼如下所示:

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

router.get('/', function(req, res, next) { 
    res.render('homeview', { title: 'Welcome', 
          user: username}); 
}); 

router.get('/:client', function(req, res, next) { 
    var theClient = req.params.client; 
    console.log(theClient) 
}); 

module.exports = router; 

,然後當我嘗試去這個網址:

http://www.localhost:3000/home/client

什麼也沒有發生。由於某些原因,它永遠不會到達第二個router.get,並且從不記錄任何東西。任何人都注意到最新錯誤?

+0

如果更改,會發生什麼你'app.use'到:'app.use(」/home',home)',然後保持你的'home.js'原樣? –

回答

0

工作液@https://github.com/rmjoia/expressRoutes

app.js

var express = require('express'), 
    app = express(), 
    port = process.env.PORT || 3000, 
    homeRouter = require('./home'); 

app.use('/home', homeRouter); 

app.route('/') 
    .all(function (request, response, next) { 
     // Do some plumbing stuff 
     next(); 
    }) 
    .get(function (request, response, next) { 
     response.send('OK GET - Hello Stack Overflow'); 
     next(); 
    }); 

app.listen(port, function (error) { 
    if (error) { 
     console.error(error.message); 
    } 
    else { 
     console.info('Server up and running. Listening on port ' + port); 
    } 
}) 

home.js

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

var router = (function (router) { 

    // define the home page route 
    router.get('/', function (req, res) { 
     res.send('home route - homepage'); 
    }); 
    // define the about route 
    router.get('/:client', function (req, res) { 
     res.send(req.params.client); 
    }); 

    return homeRouter; 
})(homeRouter); 

module.exports = router;