我正在使用Express 4.0,而我正试图创建一个路由,显示来自所有国家/地区的所有用户。
切换国家/地区我希望显示该国家/地区的所有用户。
还有两种用户(教师和学生),我也希望在那里做同样的事情。
在教师页面上,我希望向所有教师展示,并根据(之前与否)所选国家/地区,我希望看到该国家的教师......
我有几个问题这样做:
1)主页工作正常,/:countryCode
的主页工作正常,/teachers
和/students
不再加载...如果我将/:countryCode
放在所有内容之下其他页面加载...(?!?)。
2)我是否还必须创建路线,例如:/:countryCode/teachers
?或者有一种方法可以将国家代码存储在某个地方......?
3)在菜单中,似乎我必须创建2个不同的菜单,一个正常,一个带国家代码扩展......
目前我的路由是这样的:
app.get('/', homeController.index);
app.get('/:countryCode', homeController.indexByCountry);
app.get('/teachers', userController.getTeachers);
app.get('/students', userController.getStudents);
我使用参数:countryCode
来查询该国家/地区的用户。
有一种更好的方法可以创造所有这些吗?任何最佳实践?
在线我没有看到类似的东西,但我认为这样的东西应该很受欢迎。
我希望你能提供帮助。
答案 0 :(得分:0)
从我的问题中我可以看出,您希望能够在明确提供国家/地区代码时进行处理,以及您希望向所有用户(学生,教师或两者)展示或使用以前提供的国家代码。如果这不是您的意图,请告诉我。
要回答您的第一个问题,/teachers
和/students
无法加载的原因是它们与国家/地区代码匹配。我的理解是快递将按照定义的顺序对您的路线进行优先排序。
正义/:countryCode
定义在其他两条路线之上,网址/teachers
将调用homeController.indexByCountry
countryCode
参数等于"teachers"
。通过在/:countryCode
路线之上定义这些路线,它们将具有优先权并按预期工作。所以:
app.get('/', homeController.index); // Express will check this first
app.get('/teachers', userController.getTeachers); // Then this
app.get('/students', userController.getStudents); // Then this
app.get('/:countryCode', homeController.indexByCountry); // And finally this
要为教师或学生指明新的国家/地区代码,一种解决方案可能是定义/:countryCode/teachers
(或者/teachers/:countryCode
这样的路线,这对我来说更有意义。)
但是,如果您想保存国家/地区代码,可以使用会话。有一个名为express-session的快速中间件包可以帮助您实现此目的。
例如:
var express = require('express');
var session = require('express-session');
var app = express();
// Tell the express app to use the session middleware
app.use(session({
secret: 'app secret key',
resave: false,
saveUninitialized: true
}));
app.get('/', function(req, res) {
if (req.session.countryCode) { // If country code has been set
res.send('Homepage, country code is currently ' + req.session.countryCode);
} else {
res.send('Homepage, country code not set');
}
});
// Define routes for '/teachers' and '/students' etc.
app.get('/:countryCode', function(req, res) {
// Set the countryCode property of the session object to the :countryCode
// variable in the url
req.session.countryCode = req.params.countryCode;
res.send("Homepage, country code is now " + req.session.countryCode);
});
app.listen(3000);
虽然我遇到的一个问题是,当我在网络浏览器中访问服务器时,它会发送一个GET请求来查找favicon,这被解释为国家/地区代码并将其设置为' favicon.ico& #39;
对此的一种解决方法可能是在设置会话变量之前检查所提供的国家/地区代码是否符合某种特定格式,例如,如果您可能希望国家/地区代码始终为2个字符的字符串(例如," uk&# 34;或" fr")。
由于我们现在知道我们可以记住之前设置的国家/地区代码,因此您只需要一个链接到/teachers
等的菜单,您仍然可以使用会话变量中的国家/地区代码。
我希望这会有所帮助。