$ npm init$ npm install express –savevar express = require('express');
var app = express();
app.listen(3000, function() {
console.log("server started on Port 3000");
})
Take the get to de home (using request and the response):
app.get('/', fucntion(req, res) {
res.send('Hello world');
});
app.post('/users/add', function(req, res){
console.log(req.body.firstName);
res.redirect('/');
});
app.delete('/users/:id', function(req, res) {
console.log(req.params.id);
});
Return a variable in its json format: res.json(person);
use is important to put it before any request.
var logger = function (req, res, next){
console.log('Logging');
next();
}
app.use(logger);
Set the view engine
app.set('view engine', 'ejs');
// with this we can render views:
res.render('index');
Set the views folder:
app.set('views', path.join(__dirname, 'views');
Set global variables
app.use(function(req, res, next) {
res.locals.errors = null;
next();
});
Add a “public” path:
var path = require('path');
app.use(express.static(path.join(__dirname, 'public'));
I generally use 1 file per route and put all my routing files in a routes folder and leverage the Router available in express.
A route file could look like this:
var express = require('express');
var router = express.Router();
router.get('/', function (req, res) {
res.send('Hello World!');
});
module.exports = router;
Then in the app file, simply add:
var example = require('./routes/example');
app.use('/', example);
The routes in the routing file are relative to the route you declare in app.use.