Express by Examples
Routers (Controllers)
There are 4 routing methods:
- router.get() -get GET variables from URI
- router.post() -get POST variable from HTML form
- router.put() -accept put request
- router.delete() -accept delete request
router.get()
//static example - no variable is passed: /examples/static
router.get('/static', function(req, res, next) {
res.render('examples/00static');
});
//variable vdata is passed: /examples/vars/
router.get('/vars', function(req, res, next) {
//view data
var vdata=
{
title: 'Work',
name: 'John'
}
res.render('examples/01vars', vdata);
});
//variable is get from URI query: /examples/vars-from-url/?id=12&name=John&nick=Dixy
router.get('/vars-from-url', function(req, res, next) {
var id=req.query.id;
//view data
var vdata=
{
id: id,
title: 'Worker',
name: req.query.name,
nick: req.param('nick')
}
//res.send(dump(vdata));
res.render('examples/02vars_from_url', vdata);
});
//variable is get from URI parameters: /examples/vars-params/12/John
router.get('/vars-params/:id/:name', function(req, res, next) {
var id=req.params.id;
//view data
var vdata=
{
id: id,
title: 'Worker',
name: req.params.name
}
res.render('examples/02vars_from_url', vdata);
});
router.post()
//variables are sent from form /examples/static via POST method
router.post('/vars-post', function(req, res, next) {
var username=req.body.username; //via body object. Must have 'body-parser' module
var password=req.param('password', null); //via req.param() method
//view data
var vdata=
{
title: 'Worker',
username: username,
password: password
}
res.render('examples/03vars_from_form_post', vdata);
});
Properties and methods to get data
Main method is req.param('var' [, 'default value'])
Lookup is performed in the following order:
- req.params.name from /examples/John/
- req.body.username from HTML form INPUT field 'username'
- req.query.name from /examples/something/?name=John
Optionally, you can specify defaultValue to set a default value if the parameter is not found in any of the request objects.
Response
Response can be sent with:
- res.send('string')
- res.send(404) - sends status code
- res.render('view_file', vdata) -sends view file to the browser
Regular expression in routes
//variable as a regular expression inside URL: /examples/vars-regex/some/thing/123/
router.get('/vars-regex/(([a-z0-9\/]+))', function(req, res, next) {
var reg=req.params[0];
res.send(dump(req.params));
});
To replace any character use:
router.get(/(.*)/, function(req, res, next) {
var reg=req.params[0];
res.send(dump(req.params)); //return: some/thing/123/
});
Notice: Use regex without quotation marks!