2017-11-10 6 views
0

express.staticserve-index Express middlewares (https://www.npmjs.com/package/serve-index)를 사용하여 파일 목록 페이지를 제공하고 싶습니다. 루트 경로를 하드 코딩하는 대신 URL의 ID를 기반으로 데이터베이스에서 가져오고 싶습니다. Express에서 미들웨어로 req.params를 전달하는 방법

미들웨어

이 문제는 미들웨어에 req.params.id 전달하는 방법이다이

app.use('/logs/:id', express.static('C:\\log\\root\\dir'), serveIndex('C:\\log\\root\\dir')); 

처럼 사용할 수 있습니다. 이 같은 래퍼 기능을 시도했지만 작동하지 않았다 :

const mymw = (middleware, id) => { 
    const rootDir = getRootDirFromDb(id); 
    return middleware(rootDir); 
} 

app.use('/logs/:id', (req, res) => mymw(express.static, req.params.id), (req, res) => mymw(serveIndex, req.params.id)); 

답변

0

당신은 app.use에 미들웨어 정의를 전달할 수 있으며, req 개체가 미들웨어에 사용할 수 있습니다.

const mymw = (req, res, next) => { 
    // req.params is available here. 
    // you can call next() here to move to the next controller 
} 

app.use('/logs/:id', mymw, (req, res, next) => { 
    // also do stuff here 
}); 
+0

예, 나는 내 자신의 미들웨어에 req.params에서 물건을 읽을 수는 있지만'express.static'이 같은에서이 대신 루트 경로를 읽지 않는'- 제공 index' 또는 수의 이해 : 'serveIndex (rootPath)'. 어떻게 든 next()를 통해 매개 변수를 전달할 수 있습니까? 아니면 어떻게 작동합니까? –