在express中的root之后使用可选参数传递路由控制? [英] Passing route control with optional parameter after root in express?
问题描述
我正在开发一个简单的 url-shortening 应用程序,并有以下快速路线:
I'm working on a simple url-shortening app and have the following express routes:
app.get('/', function(req, res){
res.render('index', {
link: null
});
});
app.post('/', function(req, res){
function makeRandom(){
var text = "";
var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
for( var i=0; i < 3 /*y u looking at me <33??*/; i++ )
text += possible.charAt(Math.floor(Math.random() * possible.length));
return text;
}
var url = req.body.user.url;
var key = makeRandom();
client.set(key, url);
var link = 'http://50.22.248.74/l/' + key;
res.render('index', {
link: link
});
console.log(url);
console.log(key);
});
app.get('/l/:key', function(req, res){
client.get(req.params.key, function(err, reply){
if(client.get(reply)){
res.redirect(reply);
}
else{
res.render('index', {
link: null
});
}
});
});
我想从我的路由中删除 /l/
(以使我的 url 更短)并使 :key 参数可选.这是正确的方法吗:
I would like to remove the /l/
from my route (to make my url's shorter) and make the :key parameter optional. Would this be the correct way to do this:
app.get('/:key?', function(req, res, next){
client.get(req.params.key, function(err, reply){
if(client.get(reply)){
res.redirect(reply);
}
else{
next();
}
});
});
app.get('/', function(req, res){
res.render('index, {
link: null
});
});
不确定我是否需要指定我的 /
路线是要下一个"的路线.但由于我唯一的其他路线是我更新后的 /
路线,我想它会正常工作.
Not sure if I need to specify that my /
route is the one to be "nexted" to. But since my only other route would be my updated post /
route, I would imagine it would work fine.
推荐答案
这取决于 client.get 在传递 undefined 作为其第一个参数时所做的工作.
That would work depending on what client.get does when passed undefined as its first parameter.
这样的东西会更安全:
app.get('/:key?', function(req, res, next) {
var key = req.params.key;
if (!key) {
next();
return;
}
client.get(key, function(err, reply) {
if(client.get(reply)) {
res.redirect(reply);
}
else {
res.render('index', {
link: null
});
}
});
});
在回调中调用 next() 没有问题.
There's no problem in calling next() inside the callback.
根据this,处理程序按添加顺序调用, 所以只要你的下一条路由是 app.get('/', ...) 如果没有键就会被调用.
According to this, handlers are invoked in the order that they are added, so as long as your next route is app.get('/', ...) it will be called if there is no key.
这篇关于在express中的root之后使用可选参数传递路由控制?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!