我想在中间件中修改路由参数:
express = require 'express'
bodyParser = require 'body-parser'
app = express()
app.use(bodyParser.json())
// app.param(...) is deprecated
app.use (req, res, next) ->
console.log req.params.id // undefined
// req.param() is deprecated
next()
app.get '/test/:id', (req, res, next) ->
console.log(req.params.id) // correct
res.json({ id: req.params.id })
我如何在中间件中做到这一点?似乎在中间件执行期间没有解析params ...
答案 0 :(得分:1)
我找到的唯一方法是:
express = require 'express'
bodyParser = require 'body-parser'
app = express()
app.use(bodyParser.json())
middleware = (req, res, next) ->
console.log req.params.id // works!!!
next()
routeHandler = (req, res, next) ->
console.log(req.params.id) // correct
res.json({ id: req.params.id })
app.get '/test/:id', [middleware, routeHandler]
这种方法的缺点是我必须"手动"在每个路由处理程序前面加入中间件。我希望有一些类似的解决方案:解析/识别执行AFTER路由的中间件,并执行routeHandler之前。