Calling Express Route internally from inside NodeJS

前端 未结 3 1437
忘了有多久
忘了有多久 2020-12-06 04:18

I have an ExpressJS routing for my API and I want to call it from within NodeJS

var api = require(\'./routes/api\')
app.use(\'/api\', api);

3条回答
  •  -上瘾入骨i
    2020-12-06 04:53

    This is an easy way to do an internal redirect in Express 4:

    The function that magic can do is: app._router.handle()

    Testing: We make a request to home "/" and redirect it to otherPath "/other/path"

    var app = express()
    
    function otherPath(req, res, next) {
      return res.send('ok')
    }
    
    function home(req, res, next) {
      req.url = '/other/path'
      /* Uncomment the next line if you want to change the method */
      // req.method = 'POST'
      return app._router.handle(req, res, next)
    }
    
    app.get('/other/path', otherPath)
    app.get('/', home)
    

提交回复
热议问题