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

后端 未结 2 1431
再見小時候
再見小時候 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.

提交回复
热议问题