Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

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

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', routes.albums.getAlbum);
app.get('/api/albums/artwork', routes.albums.getAlbumArtwork);

and I attempt to hit them using the follow jQuery AJAX snippet:

$("#retrieveAlbumArtwork").on("click", function() {
    $.ajax({
        url: "api/albums/artwork",
        type: "GET",
        data: {
            artist: $("#albumArtist").val(),
            title: $("#albumTitle").val()
        },
        // ... callbacks and such

For some reason, this call hits the second handler, with the /:id parameter, instead of the explicit /artwork route. Swapping them like so makes them function as expected:

// music albums
app.get('/api/albums', routes.albums.getAlbums);
app.get('/api/albums/artwork', routes.albums.getAlbumArtwork);
app.get('/api/albums/:id', routes.albums.getAlbum);

Can someone explain exactly why this is happening? I would assume Express would be smart enough to identify an id param (/albums/23453243) versus a querystring (/albums/artwork?artist=artistName&title=albumTitle) and route appropriately, but this doesn't seem to be the case?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...