Express-js wildcard routing to cover everything under and including a path

前端 未结 5 1236
暖寄归人
暖寄归人 2020-12-02 16:34

I\'m trying to have one route cover everything under /foo including /foo itself. I\'ve tried using /foo* which work for everything

5条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-02 16:50

    It is not necessary to have two routes.

    Simply add (/*)? at the end of your path string.

    For example, app.get('/hello/world(/*)?' /* ... */)

    Here is a fully working example, feel free to copy and paste this into a .js file to run with node, and play with it in a browser (or curl):

    const app = require('express')()
    
    // will be able to match all of the following
    const test1 = 'http://localhost:3000/hello/world'
    const test2 = 'http://localhost:3000/hello/world/'
    const test3 = 'http://localhost:3000/hello/world/with/more/stuff'
    
    // but fail at this one
    const failTest = 'http://localhost:3000/foo/world'
    
    app.get('/hello/world(/*)?', (req, res) => res.send(`
        This will match at example endpoints: 

    ${test1}
    ${test2}
    ${test3}


    Will NOT match at:
    ${failTest}
    `)) app.listen(3000, () => console.log('Check this out in a browser at http://localhost:3000/hello/world!'))

提交回复
热议问题