skip to Main Content

Let’s say I have this GET url in my REST service:

router.get('/api/platform/:type', async (req, res) => {
    // something
}

I only want the request if :type is "windows" or "android". are there any way to do this in the url definition?

I think I’ve seen something like this before:

router.get('/api/platform/:type{windows|android}', async (req, res) => {
    // something
}

Something like that but it doesn’t quite work for me.

2

Answers


  1. You could probably use a regular expression:

    router.get(//api/platform/(?:windows|android)/, async (req, res) => {
      // something
    }
    

    See Path examples; Type: "Regular Expression"


    Here is a regex example in native JS to test out the route expression:

    const route =//api/platform/(?:windows|android)/;
    
    const requests = [
      '/api/platform/windows',
      '/api/platform/android',
      '/api/platform/macos',
      '/api/platform/linux'
    ];
    
    console.log(requests.filter(request => route.exec(request)));
    Login or Signup to reply.
  2. You can append a regular expression in parentheses to a route parameter to validate its format:

    router.get('/api/platform/:type(windows|android)', async (req, res) => {
        // something
    }
    

    To have more control over the exact string that can be matched by a route parameter, you can append a regular expression in parentheses (()):

    Route path: /user/:userId(d+)
    Request URL: http://localhost:3000/user/42
    req.params: {"userId": "42"}
    

    https://expressjs.com/en/guide/routing.html

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search