Express.js,req.params没有被调用

时间:2016-01-26 13:36:00

标签: express routing 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并且从不记录任何东西。有人注意到哪里错了?

1 个答案:

答案 0 :(得分: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;