簡體   English   中英

在express中的root之后使用可選參數傳遞路由控制?

[英]Passing route control with optional parameter after root in express?

我正在開發一個簡單的 url-shortening 應用程序,並有以下快速路線:

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 參數可選。 這是否是正確的方法:

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

不確定我是否需要指定我的/路線是要“下一個”的路線。 但由於我唯一的其他路線是我更新的帖子/路線,我想它會正常工作。

這取決於 client.get 在傳遞 undefined 作為其第一個參數時所做的工作。

像這樣的東西會更安全:

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() 沒有問題。

據此,處理程序按添加順序調用,因此只要您的下一個路由是 app.get('/', ...) 如果沒有鍵,它將被調用。

快捷版:

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

可選參數非常方便,您可以使用 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);
    }
});

在上面的代碼中, batchNo是可選的。 Express 會認為它是可選的,因為在 URL 構造之后,我給了一個“?” batchNo '/:batchNo?' 后的符號

現在我可以只使用 categoryId 和 productId 或所有三個參數來調用。

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

在此處輸入圖像描述 在此處輸入圖像描述

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM