Search code examples
node.jsexpressquery-stringexpress-router

Advanced optional routing in express


I'm Trying to build crud application using express and node.js

example query string

/table/?id=78&title=someTitle&code=3

where ID, Title And Code are optional. meaning:

  • If none entered, return all rows.
  • If id entered, return row that has that Id.
  • If code and title entered, filter rows base on input.
  • ...

But the problem is either I have to enter whole url string with null values, or the values mixed together, or express won't recognize my regex pattern (pattern is valid according to https://regexr.com website)

I've tried:

  1. https://forbeslindesay.github.io/express-route-tester/

    Route:

    /table/\??(id=)?:id?\&?(title=)?:title?\&?(code=)?:code?
    

    Path:

    /table/?id=78&title=someTitle&code=3
    

    Result:

    Image About express routing result on express-route-tester
website

  2. created my own regex:

    my own regex

    \/table\/\??(id=78)?\&?(title=someTitle)?\&?(code=3)?
    

    This will work unless I add optional express parameters.

Expected Result:

Path    
     /table/?id=78

request.params

    { id: '78'} 

---- 
Path
     /table/?code=3

request.params

    { code: '3' }

----
Path
    /table/?id=78&title=someTitle

request.params

    { id: '78', title: 'someTitle' }

PS: I know I can achieve this with matching regular expression to request.url But I want to know if there is any other way with express.


Solution

  • So Here's the answer:

    I can achieve this by using req.query instead of req.params

    req.query returns an object of inputs exactly like i wanted

    Path

    /table/?id=78&title=someTitle
    

    request.query

    { id: '78', title: 'someTitle' }