In a practice example, i'm trying to create a restfull API, very simple. The plain GET and POST methods works well, but the GET, PUT and DELETE method pointing to /api/bears/:bear_id just stay there, waiting...
// CONFIGURACION INICIAL //
// ===================== //
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var mongoose = require('mongoose');
var db = mongoose.connection;
// CONFIGURANDO APP //
// ================ //
app.use(bodyParser.urlencoded({ extended: true }))
app.use(bodyParser.json())
mongoose.connect('mongodb://localhost:27017/bears');
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function cb () {
console.log('conexion establecida');
})
var Bear = require('./models/bear_model.js');
var port = process.env.PORT || 8080; // seteo del puerto
var router = express.Router(); // instancia del ruteador
Above, the simple config, below, the snippet that is causing me problems:
router.use(function (req, res, next) { // simple logger
if (req.method === 'GET')
console.log('executing query on id %s', JSON.stringify(req.params));
else if (req.method === 'PUT')
console.log('executing query on id %s', JSON.stringify(req.params));
else
console.log('executing query on id %s', JSON.stringify(req.params));
});
router.route('/bears/:bear_id')
.get(function (req, res) {
Bear.findById(req.params.bear_id, function (err, bear) {
if (err)
res.send(err);
res.json(bear);
});
}) // end GET /bears/:bear_id
.put(function (req, res) {
Bear.findById(req.params.bear_id, function (err, bear) {
if (err)
res.send(err)
bear.name = req.body.name; // Update bear_id of Bear
bear.save(function (err) {
if (err)
res.send(err);
res.json({msg: 'Bear actualizado!'});
});
});
}) // end PUT /bears/:bear_id
.delete(function (req, res) {
Bear.remove({
_id: req.params.bear_id
}, function (err, bear) {
if (err)
res.send(err);
res.json({ msg: 'Bear eliminado' });
});
}); // end DELETE /bears/:id && router /bears/:id
app.use('/api', router); // la api usará como base el prefijo /api
Executing one route with a param log me: executing query on {}
, so, the req.params.bear_id simply is not captured, and if i change req.params by req.params.bears_id, obviously i get an undefined log, so i read de docs and think i'm doing generally well the process but don't catch the issue.
You are not calling next()
in your logger, so you're never getting to your router, which results in no response.
router.use(function (req, res, next) { // simple logger
if (req.method === 'GET')
console.log('executing query on id %s', JSON.stringify(req.params));
else if (req.method === 'PUT')
console.log('executing query on id %s', JSON.stringify(req.params));
else
console.log('executing query on id %s', JSON.stringify(req.params));
next();
});
Now the reason you are not seeing params in your logger is because params are only visible if the route definition has params. Your logger middleware doesn't define a specific route, therefore there are no params. A solution to this would be to use Router.param
router.param('bear_id', function(req, res, next, bear_id) {
if (req.method === 'GET')
console.log('executing query on id ' + bear_id);
else if (req.method === 'PUT')
console.log('executing query on id ' + bear_id);
else
console.log('executing query on id ' + bear_id);
next();
});
More simply:
router.param('bear_id', function(req, res, next, bear_id) {
console.log(req.method + ' with id ' + bear_id);
next();
});
This works this way by design, you can find more information on github: https://github.com/strongloop/express/issues/2088