How to define complex routes with named parameters in express.js?

后端 未结 2 1430
再見小時候
再見小時候 2021-02-02 16:31

I want to set up some more complex routes that can include a number of optional parameters. Preferably, I would like to use named parameters for ease of access. Here is an examp

相关标签:
2条回答
  • 2021-02-02 17:24

    It looks like you want to re-implement the query string using the URL path. My guess is that if you really wanted that, yes, you would have to write your own parsing/interpreting logic. AFAIK express path parameters are positional, whereas the query string is not. Just use a query string and express will parse it for you automatically.

    /books?category=sports&author=jack&limit=15?sortby=title
    

    That will enable you to do

    req.query.sortby
    

    You may be able to get express to do 1/2 of the parsing for you with a regular expression path like (:key/:value)* or something along those lines (that will match multiple key/value pairs), but express isn't going to then further parse those results for you.

    0 讨论(0)
  • 2021-02-02 17:33

    you can send data to view as follow:

    //in the server side ...
     app.get('/search/:qkey/:qvalue', function(req, res){
        res.write(JSON.stringify({
          qkey:req.params.qkey;
          qvalue:req.params.qvalue;
        }));
     });
    

    and in the client side... call to ajax

    $.ajax({
      type:"POST",
      url:"/search/"+qkey+"/"+qvalue,
      success: function(data){
        var string = eval("(" + data + ")");
        //you access to server response with
        console.log(string.qkey+" and "+ string.qvalue);
      }
    });    
    
    0 讨论(0)
提交回复
热议问题