2013-10-01 43 views
3

我需要在简单的node.js中使用中间件的以下express.js代码的等效代码。我需要根据url进行一些检查,并希望在自定义中间件中进行检查。与url模式匹配的Node.js

app.get "/api/users/:username", (req,res) -> 
    req.params.username 

我有下面的代码到目前为止,

app.use (req,res,next)-> 
    if url.parse(req.url,true).pathname is '/api/users/:username' #this wont be true as in the link there will be a actual username not ":username" 
    #my custom check that I want to apply 

回答

3

一招是使用这样的:

app.all '/api/users/:username', (req, res, next) -> 
    // your custom code here 
    next(); 

// followed by any other routes with the same patterns 
app.get '/api/users/:username', (req,res) -> 
    ... 

如果你只想匹配GET请求,使用app.get代替app.all

或者,如果你只是想使用某些特定路线的中间件,你可以使用这个(在JS这个时间):

var mySpecialMiddleware = function(req, res, next) { 
    // your check 
    next(); 
}; 

app.get('/api/users/:username', mySpecialMiddleware, function(req, res) { 
    ... 
}); 

编辑另一种解决方案:

var mySpecialRoute = new express.Route('', '/api/users/:username'); 

app.use(function(req, res, next) { 
    if (mySpecialRoute.match(req.path)) { 
    // request matches your special route pattern 
    } 
    next(); 
}); 

但我不明白这是如何使用app.all()作为“中间件”的。

+0

我没有中间件里面App对象。另外我只想匹配URL模式。 –

+0

@AtaurRehmanAsad第一个解决方案匹配URL模式 – robertklep

+0

是的先生。但我没有中间件的应用程序对象:) –

1

只需使用请求和响应对象就像在中间件的路由处理程序中一样,但如果实际上希望请求在中间件堆栈中继续,则调用next()

app.use(function(req, res, next) { 
    if (req.path === '/path') { 
    // pass the request to routes 
    return next(); 
    } 

    // you can redirect the request 
    res.redirect('/other/page'); 

    // or change the route handler 
    req.url = '/new/path'; 
    req.originalUrl // this stays the same even if URL is changed 
}); 
+0

我需要匹配这种模式“/ api/users /:username”,我不能用简单的比较来做到这一点。 –

+0

你可以在'req.path'上使用'.split()'并检查是否有url [1] ==='api'',url [2] ==='users''等。 – hexacyanide

+1

Yes I可以做到这一点。我只是想知道是否有一些标准的做法。任何节点库等感谢迄今的帮助。 –

1

您可以使用节点JS url-pattern模块。

制作模式:针对URL路径

var pattern = new UrlPattern('/stack/post(/:postId)'); 

匹配模式:

pattern.match('/stack/post/22'); //{postId:'22'} 
pattern.match('/stack/post/abc'); //{postId:'abc'} 
pattern.match('/stack/post'); //{} 
pattern.match('/stack/stack'); //null 

欲了解更多信息,请参见:https://www.npmjs.com/package/url-pattern