在快速根之后传递带有可选参数的路由控制?

我正在开发一个简单的网址缩短应用程序,有以下快速路线:

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/从我的路由(使我的网址更短) ,并使: 键参数可选。这样做是否正确:

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
});
});

不确定是否需要指定我的 /路由是“下一个”路由。但是因为我唯一的其他路线将是我的更新后 /路线,我可以想象它会工作得很好。

133249 次浏览

That would work depending on what client.get does when passed undefined as its first parameter.

Something like this would be safer:

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
});
}
});
});

There's no problem in calling next() inside the callback.

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 version:

"dependencies": {
"body-parser": "^1.19.0",
"express": "^4.17.1"
}

Optional parameter are very much handy, you can declare and use them easily using express:

app.get('/api/v1/tours/:cId/:pId/:batchNo?', (req, res)=>{
console.log("category Id: "+req.params.cId);
console.log("product ID: "+req.params.pId);
if (req.params.batchNo){
console.log("Batch No: "+req.params.batchNo);
}
});

In the above code batchNo is optional. Express will count it optional because after in URL construction, I gave a '?' symbol after batchNo '/:batchNo?'

Now I can call with only categoryId and productId or with all three-parameter.

http://127.0.0.1:3000/api/v1/tours/5/10
//or
http://127.0.0.1:3000/api/v1/tours/5/10/8987

enter image description here enter image description here