Search code examples
javascriptnode.jsexpressurlurl-routing

Dynamic path in express routes


I wonder how to using path in express dynamically. For example, i'm using lodash for finding a path in different file with regex method.

routes.js

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")
  })
})

On above code, i just nested the routes. But there's nothing any response. Is there any ways to do this? This method also i want to use with DB if necessary. Thanks anyway


Solution

  • Using middleware is impossible. When a request comes, expressjs will search a registered path first. So here we go why that code not running as well.

    For example, I'm as an user request : localhost:2018/test/123

    Please following my comment in below

    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")
      })
    })

    How to approach this goal then? However, we need a registering our routes inside app.use or routes.use . So far what i got, we can using loop in here.

    //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")
    })
    
    */

    Reference : Building a service API Part 4

    Thanks anyway, leave me a comment if there's something wrong with this method :D