快速路由器 - 为什么这条路由参数不能按预期工作?

时间:2015-05-21 03:52:55

标签: node.js express

我对此感到困惑。为什么我可以在网址http://localhost:1337/admin/hello/holly而不是网址http://localhost:1337/admin/users/holly看到这个?它发送文本对吗? res.send(发送'你好'到页面)。但肯定的是adminRouter.get应该拉第二个网址(在路径中使用'用户')?它基本上与我期待的相反。

这是代码段。

// route with parameters (http://localhost:1337/admin/users/:name)
    adminRouter.get('/users/:name', function(req, res) {
        res.send('hello ' + req.params.name + '!');
    });

**编辑:这里是其他路线的整个代码:

// load the express package and create our app
var express = require('express');
var app     = express();

// send our index.html file to the user for the home page
app.get('/', function(req, res) {
    res.sendFile(__dirname + '/index.html');
});

    // get an instance of the router
    var adminRouter = express.Router();

   // route middleware that will happen on every request
    adminRouter.use(function(req, res, next) {

        // log each request to the console
        console.log(req.method, req.url);

        // continue doing what we were doing and go to the route
        next(); 
    });
// route middleware to validate :name
    adminRouter.param('name', function(req, res, next, name) {
        // do validation on name here
        // blah blah validation
        // log something so we know its working
        console.log('doing name validations on ' + name);
        // once validation is done save the new item in the req
        req.name = name;
        // go to the next thing
        next();
    });
// route with parameters (http://localhost:1337/admin/users/:name)
    adminRouter.get('/users/:name', function(req, res) {
        res.send('hello ' + req.params.name + '!');
    });

    // create routes for the admin section
    // admin main page. the dashboard
    adminRouter.get('/', function(req, res) {
        res.send('I am the dashboard!');
    });

    // users page
    adminRouter.get('/users', function(req, res) {
        res.send('I show all the users!');
    });

    // posts page
    adminRouter.get('/posts', function(req, res) {
        res.send('I show all the posts!');
    });

    // apply the routes to our application
    app.use('/admin', adminRouter);

// start the server
app.listen(1337);
console.log('1337 is the magic port!');

1 个答案:

答案 0 :(得分:0)

所以这个问题的答案只是手动重启我的服务器并且问题自行解决了。

为什么它本身已经扭曲了,并且正在做的事情与他们应该做的事情相反,但是在重新启动服务器时它正常工作。