January 21st, 2015
Fast (built on top of Google's V8 engine)
Basically "javascript running on the server"
Route handling
Middleware
Client
(Users)
Server
(express.js)
Request
Response
1
GET /
Client
(Users)
Server
(express.js)
Request
Response
Static Content
HTML
IMG
CSS
JS
DB
2
Client
(Users)
Server
(express.js)
Request
Response
Static Content
HTML
IMG
CSS
JS
DB
3
var express = require ('express');
var app = express();
app.get('/', function (req, res) {
res.send('hello world');
});
app.listen(3000);
First, create a directory to hold your application
$ mkdir myapp
$ cd myapp
Create a package.json file
$ npm init
Install Express in the app directory and save it in the dependencies list
$ npm install express --save
$ touch app.js
var express = require('express');
var app = express();
app.get('/', function (req, res) {
res.send('Hello World!');
});
app.listen(3000);
The app starts a server and listens on port 3000 for connection. It will respond with "Hello World!" for request to the homepage.
Save the code in file named app.js and run it with the following command
$ node app.js
Then, load http://localhost:3000/ in the browser to see the output
Routing is determined by how the application responds to a client request on a HTTP request method (GET, POST, DELETE, PUT)
Each route has a handler function, executed when the route is matched
app.post('/', function (req, res) {
res.send('Got a POST request');
});
The following code illustrates some example routes in an app
//respond with "Hello World!" on the homepage
app.get('/', function (req, res) {
res.send('Hello World!');
});
//accept POST request on the homepage
app.post('/', function (req, res) {
res.send('Got a POST request');
});
//accept PUT request at /user
app.put('/user', function (req, res) {
res.send('Got a PUT request at /user');
});
//accept DELETE request at /user
app.delete('/user', function (req, res) {
res.send('Got a DELETE request at /user');
});
Request
Step 1
Request
Step 2
Request
Step 3
Response
Authenticate
(Passport)
Get User Information (DB)
Compile HTML File
(Render JADE Template)
Redirect
('/login');
500
Error
next()
next()
$ npm install jade --save
var express = require('express');
var app = express();
var path = require('path');
app.set('views', path.join(__dirname, 'views'));
app.set ('view engine', 'jade');
app.get('/', function (req, res) {
res.render('index');
});
app.listen(3000);
Install Jade in the app directory and save it in the dependencies list
Comment out old example and implement the code below
$ mkdir views
$ cd views
$ touch index.jade
First, create a directory to hold your application
Create a file
h1
| Hello, my name is Jade!
Save the code in file named app.js and run it with the following command
$ cd ..
$ node app.js
Then, load http://localhost:3000
in the browser to see the output
Create a h1 in the JADE file