Building web apps with
{ By: "Nirmal V",
Date: 26/08/2017
Location: Kerala Javascript Meetup, Kochi }

WHAT IS EXPRESS.JS
- Minimalist web application framework
- Runs on NodeJS
- Inspired by Sinatra
- Asynchronous
What is Node.js
Node.js® is a platform built on Chrome's JavaScript runtime for easily building fast, scalable network applications. Node.js uses an event-driven, non-blocking I/O model that makes it lightweight and efficient, perfect for data-intensive real-time applications that run across distributed devices.
Features of Node.js
- Asynchronous and Event Driven
- Very Fast
- Single Threaded but Highly Scalable
- No Buffering
Synchronous vs Asynchronous Programming
//example 1
var result = database.query("SELECT * FROM hugetable");
console.log("query finished");
console.log("Next line");
//example 2
database.query("SELECT * FROM hugetable", function(rows) {
console.log("query finished");
});
console.log("Next line");ExpressJS - How to install
npm install <package-name>npm install --save expressnpm install -g nodemonnpm initnpm install -g <package-name>ls node_modules
#(dir node_modules for windows)ExpressJS - Basics
var express = require('express');
var app = express();
app.get('/', function(req, res){
res.send("Hello world!");
});
app.listen(3000);nodemon index.jshttp://localhost:3000ExpressJS - Basics
app.listen(port, [host], [backlog], [callback]])Port
A port number on which the server should accept incoming requests.
host
Name of the domain. You need to set it when you deploy your apps to the cloud.
backlog
The maximum number of queued pending connections. The default is 511.
callback
An asynchronous function that is called when the server starts listening for requests.
ExpressJS - Routing
var express = require('express');
var app = express();
app.get('/hello', function(req, res){
res.send("Hello World!");
});
app.post('/hello', function(req, res){
res.send("You just called the post method at '/hello'!\n");
});
app.listen(3000);ExpressJS - Routing
var express = require('express');
var router = express.Router();
router.get('/', function(req, res){
res.send('GET route on things.');
});
router.post('/', function(req, res){
res.send('POST route on things.');
});
//export this router to use in our index.js
module.exports = router;var express = require('Express');
var app = express();
var things = require('./things.js');
//both index.js and things.js should be in same directory
app.use('/things', things);
app.listen(3000);ExpressJS - Routing
app.all('/test', function(req, res){
res.send("HTTP method doesn't have any effect on this route!");
});ExpressJS - Routing
var express = require('express');
var app = express();
app.get('/:id', function(req, res){
res.send('The id you specified is ' + req.params.id);
});
app.listen(3000);http://localhost:3000/123var express = require('express');
var app = express();
app.get('/things/:name/:id', function(req, res) {
res.send('id: ' + req.params.id + ' and name: ' + req.params.name);
});
app.listen(3000);http://localhost:3000/things/tutorialspoint/12345ExpressJS - Routing
var express = require('express');
var app = express();
app.get('/things/:id([0-9]{5})', function(req, res){
res.send('id: ' + req.params.id);
});
app.listen(3000);http://localhost:3000/14554Pattern Matched Routes
ExpressJS - Routing
var express = require('express');
var app = express();
//Other routes here
app.get('*', function(req, res){
res.send('Sorry, this is an invalid URL.');
});
app.listen(3000);ExpressJS - Middleware
var express = require('express');
var app = express();
//First middleware before response is sent
app.use(function(req, res, next){
console.log("Start");
next();
});
//Route handler
app.get('/', function(req, res, next){
res.send("Middle");
next();
});
app.use('/', function(req, res){
console.log('End');
});
app.listen(3000);ExpressJS - Templating
npm install --save pugapp.set('view engine', 'pug');
app.set('views','./views');<!DOCTYPE html>
<html>
<head>
<title>Hello Pug</title>
</head>
<body>
<p class = "greetings" id = "people">Hello World!</p>
</body>
</html>app.get('/first_template', function(req, res){
res.render('first_view');
});doctype html
html
head
title = "Hello Pug"
body
p.greetings#people Hello World!ExpressJS - Templating
html
head
title=name
body
h1=name
a(href = url) URLvar express = require('express');
var app = express();
app.get('/dynamic_view', function(req, res){
res.render('dynamic', {
name: "TutorialsPoint",
url:"http://www.tutorialspoint.com"
});
});
app.listen(3000);ExpressJS - Templating
html
head
title Simple template
body
include ./header.pug
h3 I'm the main content
include ./footer.pugdiv.header.
I'm the header for this website.div.footer.
I'm the footer for this website.ExpressJS - Form data
html
html
head
title Form Tester
body
form(action = "/", method = "POST")
div
label(for = "say") Say:
input(name = "say" value = "Hi")
br
div
label(for = "to") To:
input(name = "to" value = "Express forms")
br
button(type = "submit") Send my greetingsnpm install --save body-parser multerExpressJS - Form data
var express = require('express');
var bodyParser = require('body-parser');
var multer = require('multer');
var upload = multer();
var app = express();
app.get('/', function(req, res){
res.render('form');
});
app.set('view engine', 'pug');
app.set('views', './views');
// for parsing application/json
app.use(bodyParser.json());
// for parsing application/xwww-
app.use(bodyParser.urlencoded({ extended: true }));
form-urlencoded
// for parsing multipart/form-data
app.use(upload.array());
app.use(express.static('public'));
app.post('/', function(req, res){
console.log(req.body);
res.send("recieved your request!");
});
app.listen(3000);npm install --save body-parser multerExpressJS - Database
html
head
title Person
body
form(action = "/person", method = "POST")
div
label(for = "name") Name:
input(name = "name")
br
div
label(for = "age") Age:
input(name = "age")
br
div
label(for = "nationality") Nationality:
input(name = "nationality")
br
button(type = "submit") Create new personapp.get('/person', function(req, res){
res.render('person');
});npm install --save mongooseuse my_dbExpressJS - Database
var express = require('express');
var app = express();
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/my_db');
var personSchema = mongoose.Schema({
name: String,
age: Number,
nationality: String
});
var Person = mongoose.model("Person", personSchema);
app.get('/people', function(req, res){
Person.find(function(err, response){
res.json(response);
});
});
app.listen(3000);ExpressJS - Database
var express = require('express');
var app = express();
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/my_db');
var personSchema = mongoose.Schema({
name: String,
age: Number,
nationality: String
});
var Person = mongoose.model("Person", personSchema);
app.put('/people/:id', function(req, res){
Person.findByIdAndUpdate(req.params.id, req.body, function(err, response){
if(err) res.json({message: "Error in updating person with id " + req.params.id});
res.json(response);
});
});
app.listen(3000);ExpressJS - Database
var express = require('express');
var app = express();
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/my_db');
var personSchema = mongoose.Schema({
name: String,
age: Number,
nationality: String
});
var Person = mongoose.model("Person", personSchema);
app.delete('/people/:id', function(req, res){
Person.findByIdAndRemove(req.params.id, function(err, response){
if(err) res.json({message: "Error in deleting record id " + req.params.id});
else res.json({message: "Person with id " + req.params.id + " removed."});
});
});
app.listen(3000);ExpressJS - Cookies
var express = require('express');
var app = express();
app.get('/', function(req, res){
res.cookie('name', 'express').send('cookie set'); //Sets name = express
});
app.listen(3000);npm install --save cookie-parser//Expires after 360000 ms from the time it is set.
res.cookie(name, 'value', {expire: 360000 + Date.now()}); var express = require('express');
var app = express();
app.get('/clear_cookie_foo', function(req, res){
clearCookie('foo');
res.send('cookie foo cleared');
});
app.listen(3000);ExpressJS - Sessions
var express = require('express');
var cookieParser = require('cookie-parser');
var session = require('express-session');
var app = express();
app.use(cookieParser());
app.use(session({secret: "Shh, its a secret!"}));
app.get('/', function(req, res){
if(req.session.page_views){
req.session.page_views++;
res.send("You visited this page " + req.session.page_views + " times");
} else {
req.session.page_views = 1;
res.send("Welcome to this page for the first time!");
}
});
app.listen(3000);npm install --save express-sessionExpressJS - Error Handling
var express = require('express');
var app = express();
app.get('/', function(req, res){
//Create an error and pass it to the next function
var err = new Error("Something went wrong");
next(err);
});
/*
* other route handlers and middleware here
* ....
*/
//An error handling middleware
app.use(function(err, req, res, next) {
res.status(500);
res.send("Oops, something went wrong.")
});
app.listen(3000);ExpressJS - Debugging
DEBUG = express:* node index.jsDEBUG = express:application,express:router node index.jsExpressJS - Directory Structure
test-project/
node_modules/
config/
db.js //Database connection and configuration
credentials.js //Passwords/API keys for external services used by your app
config.js //Other environment variables
models/ //For mongoose schemas
users.js
things.js
routes/ //All routes for different entities in different files
users.js
things.js
views/
index.pug
404.pug
...
public/ //All static content being served
images/
css/
javascript/
app.js
routes.js //Require all routes in this and then require this file in
app.js
package.jsonFor Websites
ExpressJS - Directory Structure
test-project/
node_modules/
config/
db.js //Database connection and configuration
credentials.js //Passwords/API keys for external services used by your app
models/ //For mongoose schemas
users.js
things.js
routes/ //All routes for different entities in different files
users.js
things.js
app.js
routes.js //Require all routes in this and then require this file in
app.js
package.jsonFor RESTful APIs
Thanks!
nirmalkamath@gmail.com
http://codenirmal.com
expressjs
By nirmalvyas
expressjs
- 874