Fast, no effect middleware

I have the following code:

var express = require('express');
var app = express();
app.use(express.bodyParser());
app.use(express.cookieParser());
var port = Number(process.env.PORT || 5000);

app.get('/test/:id', function(req, res) {
    res.send(req.params);
});

app.listen(port);
console.log("Listening on port " + port);

When I clicked http://localhost:5000/test/12345in my browser, I see:

[]

But I expect to see the filled req.params object with id: 12345. Any idea what I'm doing wrong?

Thanks.

+4
source share
4 answers

, req.params , , . , . , , length . res.send JSON.stringify , , , , , . , [] .

,

var myParams = {};

Object.keys(req.params).forEach(function(key){
    myParams[key] = req.params[key];
});

res.send(myParams);

, JSON.stringify , -

app.get('/test/:0', function(req, res) {
    res.send(req.params);
});
+3

id. , 12345. , , .

 app.get('/test/:id', function(req, res) {
      console.log(req.params);
      res.send(req.params);
 });

, res.render(...), .

123451 res.send(req.params.id);.

+1

, , res.send(req.params), , req.params Array, , [].

, :

app.get('/test/:id', function(req, res) {
    res.send(require('util').inspect(req.params));
});

( URL http://localhost:5000/test/12345):

[ id: '12345' ]

, , . http://localhost:5000/test/name/234

app.get('/test/:name/:id', function(req, res) {
    res.send(require('util').inspect(req.params));
});

:

[ name: 'name', id: '234' ]

, JSON JavaScript, res.json. , json [], res.json(req.params), req.params .

, .


, 9 2014 (- 4.0.0 strong > ) req.params - , v4.0.0, .

app.get('/test/:id', function(req, res) {
    res.send(req.params);
});
+1

The problem is not your middleware. Neither BodyParser nor cookieParser provide parsing of the URL name. That being said, your code looks right to me. Are you absolutely sure that you restarted the node server after changing the code?

0
source

Source: https://habr.com/ru/post/1527951/


All Articles