- Express.js is a web framework based on the core Node.js http module and Connect (http://www.senchalabs.org/
connect/) components.\ - Express.js solves these and many other problems as abstraction and code organization. The framework
provides a model-view-controller-like (MVC-like) structure for your web apps with a clear separation of concerns
(views, routes, models)
- Express.js Installation
1. express-generator: a global NPM package that provides the command-line tool for rapid
app creation (scaffolding)
2. express: a local package module in your Node.js app’s node_modules folder
2. express: a local package module in your Node.js app’s node_modules folder
To remove installed versions:
$ sudo npm uninstall -g express-generator Or $ sudo npm uninstall -g express
To Install express:
$ npm install -g express-generator@4.0.0
- Local Express.js
$npm init //this will create package.json file
$npm install express@4.1.2 --save //this will add dependency in package.json
If we are adding dependency manually in package.json, run below command to install the added dependency.
$npm install
- Express.js Scaffolding(Creating skeleton)
express [options] [dir|appname]
options
• -e, --ejs: add EJS (http://embeddedjs.com/) engine support (by default, Jade
(http://jade-lang.com/tutorial/) is used)
• -H, --hogan: add Hogan.js engine support
• -c <engine>, --css <engine>: add stylesheet <engine> support, such as LESS
(http://lesscss.org/), Stylus (http://learnboost.github.io/stylus/) or Compass
(http://compass-style.org/) (by default, plain CSS is used)
• -f, --force: force app generation on a nonempty directory
(http://jade-lang.com/tutorial/) is used)
• -H, --hogan: add Hogan.js engine support
• -c <engine>, --css <engine>: add stylesheet <engine> support, such as LESS
(http://lesscss.org/), Stylus (http://learnboost.github.io/stylus/) or Compass
(http://compass-style.org/) (by default, plain CSS is used)
• -f, --force: force app generation on a nonempty directory
use below command to create skeleton:
express -c test express-test
To run the app(do $npm install if needed), use below:
DEBUG=my-application ./bin/ww
Go to browser and hit url http://localhost:3000/
Generated app.js file:
var express = require('express');
var path = require('path');
var favicon = require('static-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var routes = require('./routes/index');
var users = require('./routes/users');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
app.use(favicon());
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded());
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', routes);
app.use('/users', users);
/// catch 404 and forwarding to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
/// error handlers
// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: err
});
});
}
// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: {}
});
});
module.exports = app;
app.use('/users', users);
var express = require('express');
var path = require('path');
var favicon = require('static-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var routes = require('./routes/index');
var users = require('./routes/users');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
app.use(favicon());
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded());
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', routes);
app.use('/users', users);
/// catch 404 and forwarding to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
/// error handlers
// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: err
});
});
}
// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: {}
});
});
module.exports = app;
- Details of generated app.js file
app.use('/users', users);
These above syntax specify the routing with URL
Query parameters in URL:
Express.js doesn’t allow developers to route by query string arguments, we need to write some middlewares as shown below:
app.use(function (req, res, next) {
if (req.query.id) {
// process the id, then call next() when done
else if (req.query.author) {
// same approach as with id
else if (req.query.id && req.query.ref) {
// process when id and ref present
} else {
next();
}
});
if (req.query.id) {
// process the id, then call next() when done
else if (req.query.author) {
// same approach as with id
else if (req.query.id && req.query.ref) {
// process when id and ref present
} else {
next();
}
});
app.get('/about', function (req, res, next) {
// this code is executed after the query string middleware
});
// this code is executed after the query string middleware
});
Middleware as the Backbone of Express.js
app.use(favicon());
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded());
app.use(cookieParser());
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded());
app.use(cookieParser());
For example, bodyParser() and cookieParser() add HTTP request payload
(req.body) and parsed cookie data (req.cookie), respectively. And in our app.js, app.use(logger('dev')); is
tirelessly printing in the terminal pretty logs for each request.
(req.body) and parsed cookie data (req.cookie), respectively. And in our app.js, app.use(logger('dev')); is
tirelessly printing in the terminal pretty logs for each request.
- Route helpers in express.js
• all: catch every request (all methods)
• get: catch GET requests
• post: catch POST requests
• put: catch PUT requests
• del: catch DELETE requests
• get: catch GET requests
• post: catch POST requests
• put: catch PUT requests
• del: catch DELETE requests
- Start to write simple app
it000483@IND-PUN-LAP-183:~/vuclip/eclipse-workspace$ mkdir nodejs_express
it000483@IND-PUN-LAP-183:~/vuclip/eclipse-workspace$ cd nodejs_express/
it000483@IND-PUN-LAP-183:~/vuclip/eclipse-workspace/nodejs_express$ mkdir {public,public/css,public/img,public/js,db,views,views/includes,routes} it000483@IND-PUN-LAP-183:~/vuclip/eclipse-workspace/nodejs_express$ ls
db public routes views
it000483@IND-PUN-LAP-183:~/vuclip/eclipse-workspace/nodejs_express$ npm init
it000483@IND-PUN-LAP-183:~/vuclip/eclipse-workspace/nodejs_express$ ls
db package.json public routes views
it000483@IND-PUN-LAP-183:~/vuclip/eclipse-workspace/nodejs_express$ sudo npm install express@4.1.2 --save
it000483@IND-PUN-LAP-183:~/vuclip/eclipse-workspace/nodejs_express$ sudo npm install jade@1.3.1 --save
it000483@IND-PUN-LAP-183:~/vuclip/eclipse-workspace/nodejs_express$ sudo npm install mongoskin@1.4.1 --save
it000483@IND-PUN-LAP-183:~/vuclip/eclipse-workspace/nodejs_express$ sudo npm install stylus@0.44.0 --save
folder structiure:
it000483@IND-PUN-LAP-183:~/vuclip/eclipse-workspace$ cd nodejs_express/
it000483@IND-PUN-LAP-183:~/vuclip/eclipse-workspace/nodejs_express$ mkdir {public,public/css,public/img,public/js,db,views,views/includes,routes} it000483@IND-PUN-LAP-183:~/vuclip/eclipse-workspace/nodejs_express$ ls
db public routes views
it000483@IND-PUN-LAP-183:~/vuclip/eclipse-workspace/nodejs_express$ npm init
it000483@IND-PUN-LAP-183:~/vuclip/eclipse-workspace/nodejs_express$ ls
db package.json public routes views
it000483@IND-PUN-LAP-183:~/vuclip/eclipse-workspace/nodejs_express$ sudo npm install express@4.1.2 --save
it000483@IND-PUN-LAP-183:~/vuclip/eclipse-workspace/nodejs_express$ sudo npm install jade@1.3.1 --save
it000483@IND-PUN-LAP-183:~/vuclip/eclipse-workspace/nodejs_express$ sudo npm install mongoskin@1.4.1 --save
it000483@IND-PUN-LAP-183:~/vuclip/eclipse-workspace/nodejs_express$ sudo npm install stylus@0.44.0 --save
folder structiure:
app.js
var express = require('express');
var http = require('http');
var path = require('path');
var app = express();
app.set('port', process.env.PORT || 3000);
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
app.all('*', function(req, res) {
res.render('index',{msg: 'Welcome to the Practical Node.js!'});
});
http.createServer(app).listen(app.get('port'),function(){
console.log('Express.js server listening on port ' +app.get('port'));
});
index.jade
h1 hello
p Welcome to the Node.js!
Run below from terminal
it000483@IND-PUN-LAP-183:~/vuclip/eclipse-workspace/nodejs_express$ node app
Express.js server listening on port 3000
var express = require('express');
var http = require('http');
var path = require('path');
var app = express();
app.set('port', process.env.PORT || 3000);
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
app.all('*', function(req, res) {
res.render('index',{msg: 'Welcome to the Practical Node.js!'});
});
http.createServer(app).listen(app.get('port'),function(){
console.log('Express.js server listening on port ' +app.get('port'));
});
index.jade
h1 hello
p Welcome to the Node.js!
Run below from terminal
it000483@IND-PUN-LAP-183:~/vuclip/eclipse-workspace/nodejs_express$ node app
Express.js server listening on port 3000
No comments:
Post a Comment