【发布时间】:2015-05-31 13:21:33
【问题描述】:
我对此感到困惑。为什么我可以在 url http://localhost:1337/admin/hello/holly 上看到这个,但在 url http://localhost:1337/admin/users/holly 上看不到?是发短信吧? res.send(向页面发送“hello”)。但肯定 adminRouter.get 应该拉第二个网址(路径中带有“用户”一词)?它基本上与我期望的相反。
这是代码 sn-p。
// 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!');
【问题讨论】:
-
您还有其他路线吗?这些是什么?另一条路线可能在这条路线之前匹配。
-
是的,很有趣,看我上面的编辑(添加代码)。
-
抱歉,我无法理解您的问题。你的意思是,你不能打开localhost:1337/admin/hello/holly?
-
另外,Express 的哪个版本?我已经逐字复制了您的代码并使用 Express 4.12.4 运行它,它似乎可以工作。 localhost:1337/admin/hello/holly 不起作用,localhost:1337/admin/users/holly 起作用(打印“hello holly!”),这与您所描述的相反。
-
快递 4.12.4 。这太奇怪了,我停止并重新启动了服务器,现在它正在按照我认为的方式工作。现在,如果我在 url 中使用“hello”这个词,我会收到错误
Cannot GET /admin/hello/holly,如果我在 url 中使用“users”,它会打印“hello holly!”到页面。所以,它现在按预期工作。为什么在我重新启动之前它会做相反的事情?很奇怪。终端也说每次我保存文件时服务器都会重新启动,所以,我很惊讶手动停止并重新启动修复它。不,Bidhan,我的意思正好相反,但它现在正在工作。谢谢。