0

I want to modify route param inside middleware:

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

How I can do that inside middleware? It seems that params are not parsed yet during middleware execution...

user606521
  • 14,486
  • 30
  • 113
  • 204

1 Answers1

1

The only way I found is:

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]

Disadventage of this approach is that I have to "manually" incude middleware in front of each route handler. I wish there was something like in restify: middleware that executes AFTER route is parsed/recognized and BEFORE routeHandler is executed.

user606521
  • 14,486
  • 30
  • 113
  • 204