0

I can not retrieve route parameters with a simple express.Router() in an web app.

Here is a minimal example:

var http      = require('http');
const express = require('express');
const app     = express();

app.use('/hello/:world', express.Router()
    .get('/', function (req, res) {
        console.log("hello : ", req.params); //
        res.status(200).send({status: 'success', params: req.params});
}));

var port = process.env.PORT || 3000;
app.set('port', port);
var server = http.createServer(app);
server.listen(port);

I don't get any error, the res.params is simply empty when I try to reach: http://localhost:3000/hello/100 for example.

Here is the response:

{
  "status": "success",
  "params": {}
}

What I have tried so far is to set express.Router({ params: 'inherit' }) as told here: https://github.com/expressjs/express/issues/2151#issuecomment-44716623 but it doesn't change anything.

And here is the manual: http://expressjs.com/en/guide/routing.html

4

1 回答 1

0

Answer:

The thing that finally worked for me, based on these:

API doc :http://expressjs.com/en/api.html
SO example: Express Router undefined params with router.use when split across files

is to set express.Router({mergeParams: true}).

So:

var http      = require('http');
const express = require('express');
const app     = express();

app.use('/hello/:world', express.Router({mergeParams: true})
    .get('/', function (req, res) {
        console.log("hello : ", req.params); //
        res.status(200).send({status: 'success', params: req.params});
}));

var port = process.env.PORT || 3000;
app.set('port', port);
var server = http.createServer(app);
server.listen(port);

Is giving the following response over http://localhost:3000/hello/10

{
  "status": "success",
  "params": {
    "world": "10"
  }
}
于 2018-02-02T08:43:32.783 回答