What is Express.js?
Express.js is a light-weight node.js based web application framework. This JavaScript framework provides a number of flexible and useful feature in order to develop mobile as well as web application using NodeJS.


ExpressJS Features:
Following are some of the core features of Express framework −

  • Set up middlewares in order to respond to HTTP/RESTful Requests.
  • It is possible to defines a routing table in order to perform different HTTP operations.
  • Dynamically renders HTML Pages based on passing arguments to templates.
  • Provides all the feature provides by core Node.js.
  • Express prepare a thin layer, therefore, the performance is adequate.
  • Organize the web application into an MVC architecture.
  • Manages everything from routes to rendering view and preforming HTTP request.

How to setup an Express.js App?
We can follow the below step by step approach to set up an Application using ExpressJS Framework.

  • Create a folder with the same name as Project name.
  • Inside the folder create a file called package.json.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
{
“name”: “npm_smart_grocery”,
“version”: “1.0.0”,
“description”: “a sample smart grocery manager “,
“main”: “index.js”,
“”: {
“ajv”: “^4.9.0”,
“async”: “^1.4.2”,
“body-parser”: “^1.13.3”,
“cloudant”: “^1.4.0”,
“dotenv”: “^2.0.0”,
“express”: “^4.13.3”,
“express-session”: “^1.11.3”,
“memory-cache”: “^0.1.4”,
“moment”: “2.10.6”,
“passport”: “^0.3.2”,
“path-exists”: “^3.0.0”,
“r-script”: “0.0.3”,
“rio”: “^2.4.1”,
“rox”: “0.0.1-13”,
“superagent”: “^1.3.0”,
“twitter”: “^1.4.0”,
“underscore”: “^1.8.3”,
“v8”: “^0.1.0”,
“winston”: “^2.1.1”,
“winston-daily-rotate-file”: “^1.0.1”
},
“devDependencies”: {},
“scripts”: {
“test”: “echo \”Error: no test specified\” && exit 1″
},
“repository”: {
“type”: “git”,
“url”: “git+https://github.com/dahlia05/npm_smart_grocery.git
},
“author”: “dahlia”,
“license”: “ISC”,
“bugs”: {
“url”: “https://github.com/dahlia05/npm_smart_grocery/issues
},
“homepage”: “https://github.com/dahlia05/npm_smart_grocery#readme
}
  • Open command prompt on the project folder and run following command.
1 npm install

This will install all the libraries defined in package.json inside dependencies{} and the libraries are installed in node_modules folder.

  • Create a file called server.js.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
“use strict”;
 
var express = require(‘express’);
var bodyParser = require(‘body-parser’);
var session = require(‘express-session’)
 
 
//var Project = require(‘./schema’).Project;
var http = require(‘http’);
var https = require(‘https’);
 
/* Initialize express app */
var app = express();
 
var host = process.env.APP_HOST || ‘localhost’;
var port = process.env.APP_PORT || ‘3000’;
app.use(bodyParser.json());
app.use(session({
rolling: true,
saveUninitialized: true,
resave: true,
secret: config.SESSION_SECRET,
cookie: {
maxAge: 36000000,
httpOnly: false
}
}));
 
app.use(express.static(__dirname + ‘/app’));
 
var index = require(‘./routes/index’);
 
app.use (‘/’, index);
 
app.all(‘*’, function(req, res, next) {
res.set(‘Access-Control-Allow-Origin’, ‘*’);
res.set(‘Access-Control-Allow-Methods’, ‘GET, POST, DELETE, PUT’);
res.set(‘Access-Control-Allow-Headers’, ‘X-Requested-With, Content-Type’);
if (‘OPTIONS’ == req.method) return res.send(200);
next();
});
 

/* Define fallback route */
app.use(function(req, res, next) {
res.status(404).json({errorCode: 404, errorMsg: “route not found”});
});
 

/* Define error handler */
app.use(logging.errorHandler);
 

/* Start server */
app.listen(app.get(‘port’), function() {
logger.info(‘Express server listening on http://’ + app.get(‘host’) + ‘:’ + app.get(‘port’));
});

  • Create a folder called ‘routes’ inside the project folder.
  • Create a file inside ‘routes’ folder called index.js.
1
2
3
4
5
6
7
8
9
var express = require(‘express’);
var router = express.Router();
 

/* GET home page. */
router.get(‘/’, function(req, res, next) {
res.render(‘index’, { title: ‘Express’ });
});
 
module.exports = router;

  • Create a folder called ‘app’ inside the project folder and create a file inside ‘app’ folder called ‘index.html’.
  • Create a index.html file.
1 <h1> Hello World!</h1>
  • Open command prompt on the project folder and run following command.
1 node server.js

The output would be

1 2017-02-01T21:31:15.889Z – info: Express server listening on http://localhost:3000

How to config Angular 2.0 Frontend in Express.js Application?
With the Angular 2.0 the MEAN stack has a huge changes. These are the following steps to create an application using MEAN stack.

  • Install Node.js.
  • Create an express application using express generator.
  • Use the view engine as ejs, therefore, install ejs.
1 npm install –save ejs
  • Set view engine in app.js.
1
2
3
4
// view engine setup
app.set(‘views’, path.join(__dirname, ‘views’));
app.set(‘view engine’, ‘ejs’);

app.engine(‘html’, require(‘ejs’).renderFile);

  • Set the static folder.
1
2
// Set Static Folder
app.use(express.static(path.join(__dirname, ‘public’)));
  • Create the config file inside public folder following the Getting started from angular.io.
    package.json
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
{
“name”: “todoapp”,
“version”: “1.0.0”,
“scripts”: {
“start”: “tsc && concurrently \”tsc -w\” \”lite-server\” “,
“lite”: “lite-server”,
“postinstall”: “typings install”,
“tsc”: “tsc”,
“tsc:w”: “tsc -w”,
“typings”: “typings”
},
“license”: “ISC”,
“dependencies”: {
“@angular/common”: “~2.0.1”,
“@angular/compiler”: “~2.0.1”,
“@angular/core”: “~2.0.1”,
“@angular/forms”: “~2.0.1”,
“@angular/http”: “~2.0.1”,
“@angular/platform-browser”: “~2.0.1”,
“@angular/platform-browser-dynamic”: “~2.0.1”,
“@angular/router”: “~3.0.1”,
“@angular/upgrade”: “~2.0.1”,
“angular-in-memory-web-api”: “~0.1.1”,
“bootstrap”: “^3.3.7”,
“core-js”: “^2.4.1”,
“reflect-metadata”: “^0.1.8”,
“rxjs”: “5.0.0-beta.12”,
“systemjs”: “0.19.39”,
“zone.js”: “^0.6.25”
},
“devDependencies”: {
“concurrently”: “^3.0.0”,
“lite-server”: “^2.2.2”,
“typescript”: “^2.0.3”,
“typings”:”^1.4.0″
}
}

tsconfig.json

1
2
3
4
5
6
7
8
9
10
11
12
{
“compilerOptions”: {
“target”: “es5”,
“module”: “commonjs”,
“moduleResolution”: “node”,
“sourceMap”: true,
“emitDecoratorMetadata”: true,
“experimentalDecorators”: true,
“removeComments”: false,
“noImplicitAny”: false
}
}

typings.json

1
2
3
4
5
6
7
{
“globalDependencies”: {
“core-js”: “registry:dt/core-js#0.0.0+20160725163759”,
“jasmine”: “registry:dt/jasmine#2.2.0+20160621224255”,
“node”: “registry:dt/node#6.0.0+20160909174046”
}
}

system.config.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
/**
* System configuration for Angular samples
* Adjust as necessary for your application needs.
*/
(function (global) {
System.config({
paths: {

// paths serve as alias
‘npm:’: ‘node_modules/’
},

// map tells the System loader where to look for things
map: {

// our app is within the app folder
app: ‘app’,

// angular bundles
‘@angular/core’: ‘npm:@angular/core/bundles/core.umd.js’,
‘@angular/common’: ‘npm:@angular/common/bundles/common.umd.js’,
‘@angular/compiler’: ‘npm:@angular/compiler/bundles/compiler.umd.js’,
‘@angular/platform-browser’: ‘npm:@angular/platform-browser/bundles/platform-browser.umd.js’,
‘@angular/platform-browser-dynamic’: ‘npm:@angular/platform-browser-dynamic/bundles/platform-browser-dynamic.umd.js’,
‘@angular/http’: ‘npm:@angular/http/bundles/http.umd.js’,
‘@angular/router’: ‘npm:@angular/router/bundles/router.umd.js’,
‘@angular/forms’: ‘npm:@angular/forms/bundles/forms.umd.js’,

// other libraries
‘rxjs’:                      ‘npm:rxjs’,
‘angular-in-memory-web-api’: ‘npm:angular-in-memory-web-api’,
},

// packages tells the System loader how to load when no filename and/or no extension
packages: {
app: {
main: ‘./main.js’,
defaultExtension: ‘js’
},
rxjs: {
defaultExtension: ‘js’
},
‘angular-in-memory-web-api’: {
main: ‘./index.js’,
defaultExtension: ‘js’
}
}
});
})(this);

  • Now run ‘npm install’ command to install all the necessary dependencies.
  • Change the ‘views/index.html’ folder with the following code.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
<html>
<head>
<title>MyTaskList</title>
<meta charset=”UTF-8″>
<meta name=”viewport” content=”width=device-width, initial-scale=1″>
<link rel=”stylesheet” href=”bower_components/bootstrap/dist/css/bootstrap.css”>
<link rel=”stylesheet” href=”styles.css”>
<!– 1. Load libraries –>
<!– Polyfill(s) for older browsers –>
<script src=”node_modules/core-js/client/shim.min.js”></script>
<script src=”node_modules/zone.js/dist/zone.js”></script>
<script src=”node_modules/reflect-metadata/Reflect.js”></script>
<script src=”node_modules/systemjs/dist/system.src.js”></script>
<!– 2. Configure SystemJS –>
<script src=”systemjs.config.js”></script>
<script>
System.import(‘app’).catch(function(err){ console.error(err); });
</script>
</head>
<!– 3. Display the application –>
<body>
<my-app>Loading…</my-app>
</body>
</html>
  • Create an app.component.
1
2
3
4
5
6
7
8
9
10
11
import { Component } from ‘@angular/core’;
import {TaskService} from ‘./services/task.service’;
 
@Component({
moduleId: module.id,
selector: ‘my-app’,
templateUrl: ‘app.component.html’,
providers:[TaskService]
})
 
export class AppComponent { }
  • Add the template.
1
2
3
4
5
<div class=”container”>
<h1>MyTodoList</h1>
<hr>
 
</div>
  • Create Angular App module in ‘public/app/app.module.ts’.
1
2
3
4
5
6
7
8
9
10
11
12
import { NgModule }      from ‘@angular/core’;
import { BrowserModule } from ‘@angular/platform-browser’;
import {HttpModule} from ‘@angular/http’;
import {FormsModule} from ‘@angular/forms’;
import {AppComponent} from ‘./app.component’;
 
@NgModule({
imports:      [ BrowserModule, HttpModule, FormsModule ],
declarations: [AppComponent, TasksComponent],
bootstrap: [AppComponent]
})
export class AppModule { }
  • Now on the browser it would look like:
  • Similarly add other angular module to the angular app.

Explain Routing in Express.js in details?

  • Create a file called routes.js  containing all the routes of the application.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
/**
* Contains all application routes.
* @version 1.0
*/
‘use strict’;
 
module.exports = {
‘/member/register’: {
post: {
controller: ‘MemberController’,
method: ‘register’,
public: true
}
},
‘/member/login’: {
post: {
controller: ‘MemberController’,
method: ‘login’,
public: true
}
},
‘/member/logout’: {
post: {
controller: ‘MemberController’,
method: ‘logout’,
public: true
}
},
‘/member/profile/:profileId’: {
post: {
controller: ‘MemberController’,
method: ‘saveProfile’,
public: false
},
get: {
controller: ‘MemberController’,
method: ‘getProfile’,
public: false
},
delete: {
controller: ‘MemberController’,
method: ‘deleteProfile’,
public: false
}
}
};
  • Create a file called MemberController.js.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
/**
* This controller exposes REST actions for managing Games.
*
* @version 1.0
*/
‘use strict’;
 
var async = require(‘async’);
var MemberService = require(‘../services/MemberService’);
var helper = require(‘../helpers/helper.js’);
var DBService = require(‘../services/DBService’);
var UserAlreadyExistsError = require(‘../helpers/errors’).UserAlreadyExistsError;
/**
* register a member
* @param {Object} req the request
* @param {Object} res the response
* @param {Function} next the next middleware
*/
function register(req, res, next) {
var user =req.body;
async.waterfall([
function(cb) {
var query = { selector: { email: user.email }, limit: 1};
DBService.find(query , cb);
},
function(data, cb) {
if (typeof data.docs!== ‘undefined’ && data.docs.length > 0)
cb(new UserAlreadyExistsError());
else
{
MemberService.registerMember(user,cb);
}
},
function(result) {
res.json(helper.buildResponse(result));
}], function(err) {
if (err) {
return next(err);
}
});
}
 

/**
* Login.
* @param {Object} req the request
* @param {Object} res the response
* @param {Function} next the next middleware
*/

function login(req, res, next) {
var username = req.body.authInfo.username;
var password = req.body.authInfo.password;
async.waterfall([
function (cb) {
MemberService.loginMember(username,password, cb);
},
function (response, cb) {
var query = { selector: { email: username }, limit: 1};
DBService.find(query, cb);
},
function (data, cb) {
var user = {
“username”: username,
“isLoggedIn”: true
};
req.session.user = user;
res.json({
MemberInfo: user
});
cb();
}], function (err) {
if (err) {
req.session.destroy();
return next(err);
}
});
}
 
/**
* Logout.
* @param {Object} req the request
* @param {Object} res the response
* @param {Function} next the next middleware
*/
function logout(req, res, next) {
req.session.user = {};
res.end();
}
 
/**
* save profile
*
*/
function saveProfile(req, res, next) {
var profile = req.body;
var profileId = req.params.profileId;
var username = req.body.authInfo.username;
async.waterfall([
function (cb) {
MemberService.validateprofile(profile, cb);
}, function (profile, cb) {
MemberService.saveProfile(profile, profileId, cb);
},
function(result) {
res.json(helper.buildResponse({
profileId: profileId,
message: result
}));
}], function (err) {
if (err) {
req.session.destroy();
return next(err);
}
});
}
 
/**
* get profile
*
*/
function getProfile(req, res, next) {
var profileId = req.params.profileId;
var username = req.body.authInfo.username;
async.waterfall([
function (cb) {
MemberService.getProfile(profileId, cb);
},
function(result) {
res.json(helper.buildResponse(result));
}], function (err) {
if (err) {
req.session.destroy();
return next(err);
}
});
}
 
/**
* delete profile
*
*/
function deleteProfile(req, res, next) {
var profileId = req.params.profileId;
async.waterfall([
function (cb) {
MemberService.deleteProfile(profileId, cb);
},
function(result) {
res.json(helper.buildResponse(result));
}], function (err) {
if (err) {
req.session.destroy();
return next(err);
}
});
}
 
module.exports = {
login: login,
register:register,
logout: logout,
saveProfile:saveProfile,
getProfile:getProfile,
deleteProfile:deleteProfile
 
};

  • Create a file called MemberService.js and DatabaseService.js would be created.
  • In server.js add the following code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
/* Load all routes */
_.each(require(“./routes”), function (verbs, url) {
_.each(verbs, function (def, verb) {
 
var method = require(“./controllers/” + def.controller)[def.method];
if (!method) {
throw new Error(def.method + ” is undefined”);
}
var signature = def.controller + “#” + def.method;
var actions = [];
actions.push(function(req, res, next) {
req.signature = signature;
return next();
});

/* If route is not public, check for user session first */
if (!def.public) {
actions.push(function(req, res, next) {
var user = req.session.user;
if (!user || !(user.isLoggedIn)) {
return next(new NotAuthenticatedError(‘You need to login first.’));
}
next();
});
}
actions.push(function(req, res, next) {
try {
logger.info(‘ENTER ‘ + signature);
method(req, res, next);
logger.info(‘EXIT ‘ + signature);
} catch(e) {
logging.logError(signature, e);
next(e);
}
});
app[verb](url, actions);
});
});

  • Now any  of the route defined in routes.js can be accessed.

Explain Logging in Express.js? Give a practical example to demonstrate?
With Express 4.0, the application can be generated using express-generator and it includes morgan as the logger:

  • Create express app using express generator.
  • The middleware in app.js is already added.
1 var logger = require(‘morgan’);
  • Create the local middleware.
1 var logger = morgan(‘combined’);
  • Otherwise, If logging is need to be added to a log file.
    Add fs to app.js
1 var fs = require(‘fs’)

Add the file

1 var log_file = fs.createWriteStream(path.join(__dirname, log.log’), {flags: ‘a’})

Create the middleware

1 Var logger = morgan(‘combined’, {stream: log_file})
  • Make sure logging will be enabled only in development environment.
1 app.use(logger(‘dev’));
  • Now if we run from the browser we can see that every request is being logged.
1
2
3
4
5
6
7
GET /dsfsdf 500 387.461 ms – 1144
GET /stylesheets/style.css 304 3.383 ms – –
GET / 304 40.564 ms – –
GET /stylesheets/style.css 304 1.791 ms – –
GET /todos 200 1.397 ms – 51
GET /todos/new 304 62.912 ms – –
GET /stylesheets/style.css 304 0.397 ms – –

Learn to Build a Shopping Cart using NodeJS
This mini NodeJS course will help you learn how to design your own eCommerce website using NodeJS, Express and Kraken. NodeJS is a brilliant open-source JavaScript runtime environment that allows developers to create powerful and dynamic server-side web applications.

In this project-based course, you will build an entire Bookstore from scratch. You will be able to add, edit and delete books to the backend and customers will be able to browse, add and delete books from their cart as well as purchase it using Paypal.

Take this Course Online Now


How to config properties in Express Application?
In an ExpressJS Application, we can config properties in following two ways:


With Process.ENV?

  • Create a file with name ‘.env’ inside the project folder.
  • Add all the properties in ‘.env’ file.
  • In server.js any of the properties can be used as:
1
2
3
var host = process.env.APP_HOST
app.set(‘host’, host);
logger.info(‘Express server listening on http://’ + app.get(‘host’));

With RequireJs?

  • Create a file called  ‘config.json’ inside a folder called ‘config’ inside the project folder.
  • Add config properties in config.json.
1
2
3
4
{
“env”:”development”,
“apiurl”:”http://localhost:9080/api/v1/
}
  • Use require to access the config.json file.
1 var config = require(‘./config/config.json’);

How to allow CORS in ExpressJS? Explain with an example.
In order to allow CORS in Express.js,  add the following code in server.js:

1
2
3
4
5
6
7
app.all(‘*’, function(req, res, next) {
res.set(‘Access-Control-Allow-Origin’, ‘*’);
res.set(‘Access-Control-Allow-Methods’, ‘GET, POST, DELETE, PUT’);
res.set(‘Access-Control-Allow-Headers’, ‘X-Requested-With, Content-Type’);
if (‘OPTIONS’ == req.method) return res.send(200);
next();
});

How to redirect 404 errors to a page in ExpressJS?
In server.js add the following code to redirect 404 errors back to a page in our ExpressJS App:

1
2
3
4
/* Define fallback route */
app.use(function(req, res, next) {
res.status(404).json({errorCode: 404, errorMsg: “route not found”});
});

Explain Error Handling in Express.js using an example?
From Express 4.0 Error handling is much easier. The steps are as following:

  • Create an express.js application and as there is no built-in middleware like errorhandler in express 4.0, therefore, the middleware need to be either installed or need to create a custom one.

Create a Middleware:

  • Create a middleware as following:
1
2
3
4
5
6
7
8
9
10
// error handler
app.use(function(err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get(‘env’) === ‘development’ ? err : {};
 
// render the error page
res.status(err.status || 500);
res.render(‘error’);
});

Install Error Handler Middleware:

  • Install errorhandler.
1 npm install errorhandler –save
  • Create a variable.
1 var errorhandler = require(‘errorhandler’)
  • Use the middleware as following:
1
2
3
4
5
6
7
8
9
10
11
12
13
if (process.env.NODE_ENV === ‘development’) {
// only use in development
app.use(errorhandler({log: errorNotification}))
}
function errorNotification(err, str, req) {
var title = ‘Error in ‘ + req.method + ‘ ‘ + req.url
notifier.notify({
title: title,
message: str
})
}

How to implement File uploading and downloading with Express?
Below we have explained the process to upload as well as download a file with ExpressJS App.
Upload File in Express.js:

  • Install formidable.
1 npm install –save formidable
  • Add the following code in server.js in order to upload a file.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
var formidable = require(‘formidable’);
app.post(‘/’, function (req, res){
var form = new formidable.IncomingForm();
 
form.parse(req);
 
form.on(‘fileBegin’, function (name, file){
file.path = __dirname + ‘/uploads/’ + file.name;
});
 
form.on(‘file’, function (name, file){
console.log(‘Uploaded Successfully! ‘ + file.name);
});
res.sendFile(__dirname + ‘/index.html’);
});
  • Update the index.html as following:
1
2
3
4
5
6
7
8
9
10
11
12
<!DOCTYPE html>
<html>
<head>
<title>Simple File Upload Example</title>
</head>
<body>
<form action=”/” enctype=”multipart/form-data” method=”post”>
<input type=”file” name=”upload” multiple>
<input type=”submit” value=”Upload”>
</form>
</body>
</html>

Download File in Express.js:

  • Add the following code in server.js.
1
2
3
4
5
6
7
var router = express.Router();
// …
router.get(‘/:id/download’, function (req, res, next) {
var filePath = “/my/file/path/…”;
var fileName = “samplefile.pdf”;
res.download(filePath, fileName);
});

How to enable debugging in express app?
In different Operating Systems, we have following commands:

On Linux the command would be as follows:

1 $ DEBUG=express:* node index.js

On Windows the command would be:

1 set DEBUG=express:* & node index.js

From Webstrome IDE

1 C:\Program Files (x86)\JetBrains\WebStorm 2016.2.4\bin\runnerw.exe” “C:\Program Files\nodejs\node.exe” –debug-brk=61081 –expose_debug_as=v8debug E:\Development\nodejd\library\bin\www

Back to top


How to implement JWT authentication in Express app ? Explain with example.

  • Create a folder called ‘keys’ inside project folder.
  • Install some dependencies as following:
1 Npm install jsonwebtoken –save
  • Add the login router routes/index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
router.post(‘/login, function(req, res) {
// find the user
User.findOne({
name: req.body.username
}, function(err, res) {
if (err) throw err;
if (!res) {
res.json({ success: false, message: Login failed.’ });
} else if (res) {
 
// check if password matches
if (res.password != req.body.password) {
res.json({ success: false, message: Login  failed. Wrong password.’ });
} else {
var token = jwt.sign(res, app.get(‘superSecret’), {
expiresInMinutes: 1600
});
// return the information including token as JSON
res.json({
success: true,
message: ‘Valid token!’,
token: token
});
}
}  });
});
  • Use the token in application
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
jwt = require(“express-jwt”);
app.use(function(req, res, next) {
var token = req.body.token || req.query.token || req.headers[‘x-access-token’];
if (token) {
jwt.verify(token, app.get(‘superSecret’), function(err, decoded) {
if (err) {
return res.json({ success: false, message: ‘Invalid token.’ });
} else {
req.decoded = decoded;
next();
}
});
} else {
return res.status(403).send({
success: false,
message: ‘No token given.’
});
}
});
Back to list

Leave a Reply

Your email address will not be published. Required fields are marked *