2013-10-01 5 views
3

미들웨어에서 사용할 수있는 간단한 node.js에 express.js 코드와 동등한 코드가 필요합니다. URL에 따라 몇 가지 검사를해야하며 사용자 정의 미들웨어에서 수행하려고합니다. 만, GET 요청을 일치 대신 app.get를 사용하려면URL 패턴과 일치하는 Node.js

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) -> 
    ... 

:

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.

또는, 특정 특정 노선에서의 미들웨어를 사용하려는 경우, 당신은이 (JS이 시간) 사용할 수 있습니다

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(); 
}); 

: 다른 솔루션

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

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

편집을 그러나 나는 이것이 '미들웨어'로 app.all()을 사용하여 어떻게 뛰는 지 보지 못합니다.

+0

내가 미들웨어 내부 응용 프로그램 개체가 없습니다. 또한 URL 패턴과 일치 시키려고합니다. –

+0

@AtaurRehman 첫 번째 해결책은 URL 패턴과 일치합니다. – robertklep

+0

예. 하지만 midleware에서 응용 프로그램 객체가 없습니다 :) –

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

예 그럴 수있어. 나는 그 일을하는 표준 방법이 있는지 궁금 할뿐입니다. 모든 노드 라이브러리 등. 지금까지 도움을 주셔서 감사합니다. –

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

관련 문제