2017-10-15 5 views
2

급행에있는 경로를 동적으로 사용하는 방법 생각해보십시오. 예를 들어, 정규식 메서드를 사용하여 다른 파일에서 경로를 찾는 데 lodash를 사용하고 있습니다. 급행 노선에있는 동적 인 경로

const json = require('./routes.json') 
 
const _ = require('lodash') 
 
routes.use(function(req, res, next) { 
 

 
    let str = req.path 
 
    let path = str.split('/')[1] 
 

 
    // [Request] => /test/123 
 
    console.log(path) 
 
    // [Result] => test 
 

 
    let test = _.find(json.routes, function(item) { 
 
    return item.path.match(new RegExp('^/' + path + '*')) 
 
    }) 
 
    console.log(test) 
 
    //{"path" : "/test/:id", "target" : "localhost:2018", "message" : "This is Test Response" }, 
 

 
    routes.get(test.path, function(req, res) { 
 
    res.json("Done") 
 
    }) 
 
})
위의 코드에

routes.js 
, 난 그냥 경로를 중첩. 그러나 아무런 반응이 없습니다. 이것을 할 수있는 방법이 있습니까? 이 방법은 또한 필요한 경우 DB와 함께 사용하고 싶습니다. 어쨌든 고마워요

답변

0

미들웨어를 사용할 수 없습니다. 요청이 오면 expressj는 먼저 등록 된 경로를 검색합니다. 그래서 여기에 우리는 그 코드가 잘 돌아 가지 않는 이유를 설명합니다. 예를 들어

, 나는 사용자의 요청으로 해요 :

하십시오 localhost:2018/test/123는이 목표에 접근하는 방법

const json = require('./routes.json') 
 
const _ = require('lodash') 
 
routes.use(function(req, res, next) { 
 

 
    let str = req.path 
 
    let path = str.split('/')[1] 
 

 
    // [Request] => /test/123 
 
    console.log(path) 
 
    // [Result] => test 
 

 
    let test = _.find(json.routes, function(item) { 
 
    return item.path.match(new RegExp('^/' + path + '*')) 
 
    }) 
 
    console.log(test) 
 
    //{"path" : "/test/:id", "target" : "localhost:2018", "message" : "This is Test Response" }, 
 

 
    //And now, the routes has been registered by /test/:id. 
 
    //But, you never get response because you was hitting the first request and you need a second request for see if that works. But you can't do a second request, this method will reseting again. Correctmeifimwrong 
 

 
    routes.get(test.path, function(req, res) { 
 
    res.json("Done") 
 
    }) 
 
})

아래

에 내 의견을 다음? 그러나 app.use 또는 routes.use 안에 노선을 등록해야합니다. 지금까지 내가 가진 것은 루프를 사용할 수 있습니다.

//Now, we registering our path into routes.use 
 
_.find(json.routes, function(item) { 
 
    routes.use(item.path, function(req, res) { 
 
    res.json("Done") 
 
    }) 
 
}) 
 

 
//The result become 
 

 
/** 
 
* routes.use('/test:id/', function(req, res, next){ 
 
    res.json("Done") 
 
}) 
 

 
routes.use('/hi/', function(req, res, next){ 
 
    res.json("Done") 
 
}) 
 

 
*/

참조 : D

:이 방법에 문제가 있다면 Building a service API Part 4

감사 어쨌든, 나에게 코멘트를 남겨