Node.js的防爆preSS路线命名和排序:precedence是如何确定的? [英] Node.js Express route naming and ordering: how is precedence determined?
问题描述
说我得到了一些让我的前preSS申请途径:
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);
和我尝试使用jQuery的跟踪AJAX片段来打他们:
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
由于某些原因,这个调用打第二个处理器,使用 /:而不是明确
/图稿$ C ID
参数, $ C>路线。交换他们像这样使得它们的功能预期:
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);
有人能解释到底为什么会这样?我会假设前preSS将足够聪明,以确定一个id参数( /相册/ 23453243
)与查询字符串( /专辑/插图?艺术家= ARTISTNAME&放大器;标题= ALBUMTITLE
)和路由适当,但这似乎并没有出现这种情况。
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?
推荐答案
没有事实并非如此。 :ID
将匹配任何东西。因此, / API /专辑/作品
是完全有效的那场比赛。防爆preSS不支持正则表达式匹配也。所以,你可以使用正则表达式做出明确的数字匹配的路由。
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.
另一种选择是使用app.param这里API文档中解释
HTTP://ex$p$pssjs.com/api.html#app.param
Another option is using app.param as explain in the API documentation here http://expressjs.com/api.html#app.param
这允许您定义路由器匹配PARAMS,所以你可以有一个像网址 / API /专辑/:ALBUMID
,其中:ALBUMID
必须是数字,你也可以在这一点上验证一个 ALBUMID
如果你想了。
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.
这篇关于Node.js的防爆preSS路线命名和排序:precedence是如何确定的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!