Node.js Express route naming and ordering: how is precedence determined?

前端 未结 1 997
时光取名叫无心
时光取名叫无心 2020-12-04 01:12

Say I\'ve got a few GET routes on my Express application:

// music albums
app.get(\'/api/albums\', routes.albums.getAlbums);
app.get(\'/api/albums/:id\', rou         


        
相关标签:
1条回答
  • 2020-12-04 01:59

    No it isn't. :id will match anything. So /api/albums/artwork is totally valid for that match. Express does support RegExp match also. So you could make an explicit numeric matching route using RegExp.

    Another option is using app.param as explained in the API documentation here: https://expressjs.com/en/api.html#app.param

    This allows you to define matching params for the router so you could have a URL like /api/albums/:albumId where :albumId has to be numeric, you could also validate an albumId at this point if you wished too.

    But in all, the second way you are doing it fairly normal, generally I put static routes at the top, then dynamic routes, catch all, then error handlers.

    0 讨论(0)
提交回复
热议问题