Hi im recently learning node.JS and the express module, i found this great example link
but when i try to update their dependencies to express 4.0 the example stop working i understand that in express 4.0 app.configure and app.router, method override y body parser is deprecated but when i do every fix, removing those lines and updating my dependencies like
"dependencies": {
"express": "~4.0.0",
"morgan": "~1.0.0",
"body-parser": "~1.0.0",
"method-override": "~1.0.0"
}
i keep getting validation and undefined errors, i will really appreacite some help with this, because soon i will need to build an app based in this module and i hope i can use their last version
this is the complete original code:
server.js
// Incluímos las dependencias que vamos a usar
var express = require("express"),
app = express(),
http = require("http"),
server = http.createServer(app),
mongoose = require("mongoose");
// Configuramos la app para que pueda realizar métodos REST
app.configure(function () {
app.use(express.bodyParser()); // JSON parsing
app.use(express.methodOverride()); // HTTP PUT and DELETE support
app.use(app.router); // simple route management
});
routes = require('./routes/tshirts')(app);
// Conexión
mongoose.connect('mongodb://localhost/tshirts', function(err, res) {
if(err) {
console.log('ERROR: connecting to Database. ' + err);
} else {
console.log('Connected to Database');
}
});
// petición GET del root que sólo muestre "Hello world!"
app.get('/', function(req, res) {
res.send("Hello world!");
});
// El servidor escucha en el puerto 3000
server.listen(3000, function() {
console.log("Node server running on http://localhost:3000");
});
and routes.js
/ tshirts.js
//======================================================================================
module.exports = function(app) {
var Tshirt = require('../models/tshirt.js');
//GET - Return all tshirts in the DB
findAllTshirts = function(req, res) {
console.log("GET - /tshirts");
return Tshirt.find(function(err, tshirts) {
if(!err) {
return res.send(tshirts);
} else {
res.statusCode = 500;
console.log('Internal error(%d): %s',res.statusCode,err.message);
return res.send({ error: 'Server error' });
}
});
};
//GET - Return a Tshirt with specified ID
findById = function(req, res) {
console.log("GET - /tshirt/:id");
return Tshirt.findById(req.params.id, function(err, tshirt) {
if(!tshirt) {
res.statusCode = 404;
return res.send({ error: 'Not found' });
}
if(!err) {
// Send { status:OK, tshirt { tshirt values }}
return res.send({ status: 'OK', tshirt:tshirt });
// Send {tshirt values}
// return res.send(tshirt);
} else {
res.statusCode = 500;
console.log('Internal error(%d): %s',res.statusCode,err.message);
return res.send({ error: 'Server error' });
}
});
};
//POST - Insert a new Tshirt in the DB
addTshirt = function(req, res) {
console.log('POST - /tshirt');
console.log(req.body);
var tshirt = new Tshirt({
model: req.body.model,
images : req.body.images,
style: req.body.style,
size : req.body.size,
colour: req.body.colour,
price: req.body.price,
summary: req.body.summary
});
tshirt.save(function(err) {
if(!err) {
console.log("Tshirt created");
return res.send({ status: 'OK', tshirt:tshirt });
} else {
console.log(err);
if(err.name == 'ValidationError') {
res.statusCode = 400;
res.send({ error: 'Validation error' });
} else {
res.statusCode = 500;
res.send({ error: 'Server error' });
}
console.log('Internal error(%d): %s',res.statusCode,err.message);
}
});
res.send(tshirt);
};
//PUT - Update a register already exists
updateTshirt = function(req, res) {
console.log("PUT - /tshirt/:id");
console.log(req.body);
return Tshirt.findById(req.params.id, function(err, tshirt) {
if(!tshirt) {
res.statusCode = 404;
return res.send({ error: 'Not found' });
}
if (req.body.model != null) tshirt.model = req.body.model;
if (req.body.price != null) tshirt.price = req.body.price;
if (req.body.images != null) tshirt.images = req.body.images;
if (req.body.style != null) tshirt.style = req.body.style;
if (req.body.size != null) tshirt.size = req.body.size;
if (req.body.colour != null) tshirt.colour = req.body.colour;
if (req.body.summary != null) tshirt.summary = req.body.summary;
return tshirt.save(function(err) {
if(!err) {
console.log('Updated');
return res.send({ status: 'OK', tshirt:tshirt });
} else {
if(err.name == 'ValidationError') {
res.statusCode = 400;
res.send({ error: 'Validation error' });
} else {
res.statusCode = 500;
res.send({ error: 'Server error' });
}
console.log('Internal error(%d): %s',res.statusCode,err.message);
}
res.send(tshirt);
});
});
}
//DELETE - Delete a Tshirt with specified ID
deleteTshirt = function(req, res) {
console.log("DELETE - /tshirt/:id");
return Tshirt.findById(req.params.id, function(err, tshirt) {
if(!tshirt) {
res.statusCode = 404;
return res.send({ error: 'Not found' });
}
return tshirt.remove(function(err) {
if(!err) {
console.log('Removed tshirt');
return res.send({ status: 'OK' });
} else {
res.statusCode = 500;
console.log('Internal error(%d): %s',res.statusCode,err.message);
return res.send({ error: 'Server error' });
}
})
});
}
//Link routes and functions
app.get('/tshirts', findAllTshirts);
app.get('/tshirt/:id', findById);
app.post('/tshirt', addTshirt);
app.put('/tshirt/:id', updateTshirt);
app.delete('/tshirt/:id', deleteTshirt);
}
Thanks!
While you don't mention what errors you are getting, there are very significant differences between Express 3.x and Express 4.x so you can't just update your versions and leave it at that.
Since you aren't doing much with middleware it appears, the big change that is impacting you is that routing is rather different now. Instead of your app.get(...), app.post(...) etc calls in your routes.js you will create a router:
var router = express.Router();
And then you add the routes to the router.
router.get('/',function(req,res){ ...});
router.put('/:id',someFunc);
At the end of this, you'd just export your router object. Back in app.js, you'd do something like:
var routes = require('./routes/tshirts')
app.use('/tshirt',routes);
In any case, you should really look at the official migration guide, as well as other 3rd party guides like this one from Scotch.io
For Express 4, app.configure() is no longer needed. In addition, bodyParser and methodOverride (among many other) middlewares are not included with Express 4. You need to install and require them separately. The existing code:
app.configure(function () {
app.use(express.bodyParser()); // JSON parsing
app.use(express.methodOverride()); // HTTP PUT and DELETE support
app.use(app.router); // simple route management
});
should be changed to:
var bodyParser = require('body-parser');
var methodOverride = require('method-override');
:
:
app.use(bodyParser()); // JSON parsing
app.use(methodOverride()); // HTTP PUT and DELETE support
app.use(app.router); // simple route management
Don't forget to install body-parser and method-override middlewares.