Hey all! This and next articles will be devoted to various themes on development within the context of one app that we will consequently improve. This app is a web chat. Not a simple one, but the web chat that should demonstrate correct configuration, how to create common pages using Node.js and the Express framework, how to do templating, JSON
service, authorization, chat, Socket
, how to work with a database, to name just a few. The articles will contain materials created by using the framework version Express 3, the current version of Express 4. Out of date features of Express 3 are not used in the articles, so the only cardinal difference in Express 4 is that a number of libraries have been taken out of the framework – see Migrating from 3.x to 4.x. If you want to follow our lessons, we recommend:
npm i express@3
And your further transition to the Version 4 will be obvious.
So, let us start with Express technology, and we will get familiar with other aspects mentioned above while developing our chat.
So, an empty directory. To create our own website, we will use the Express system :
npm install i -g [email protected]
Express is a Node.js framework that is mostly used for creating websites and online services. Let us install it globally because we will need a specialized Express utility. It enables to quickly generate the website structure, its main files
express –help
shows options. We will need:
express –s –e
which means we will add both the support of sessions and the template engine --ejs
to our new website. The way how it is included and works will be explored in the process. So, everything’s done.
Open it in WebStorm. You can use any other editor convenient for you. So, look what’s been generated. App.js
is a main file, and we will analyze its details very soon.
/** * Module dependencies. */ var express = require('express'); var routes = require('./routes'); var user = require('./routes/user'); var http = require('http'); var path = require('path'); var app = express(); // all environments app.set('port', process.env.PORT || 3000); app.set('views', __dirname + '/views'); app.set('view engine', 'ejs'); app.use(express.favicon()); app.use(express.logger('dev')); app.use(express.bodyParser()); app.use(express.methodOverride()); app.use(express.cookieParser('your secret here')); app.use(express.session()); app.use(app.router); app.use(express.static(path.join(__dirname, 'public'))); // development only if ('development' == app.get('env')) { app.use(express.errorHandler()); } app.get('/', routes.index); app.get('/users', user.list); http.createServer(app).listen(app.get('port'), function(){ console.log('Express server listening on port ' + app.get('port')); });
Package.json
–is a main file of the app. Add the title of our project there.
{ "name": "chat", "version": "0.0.1", "private": true, "scripts": { "start": "node app.js" }, "dependencies": { "express": "3.3.8", "ejs": "*" } }
To launch the project you need dependencies
. So, we open the console again and enter:
npm i
Everything contained in рackage.json
will be installed in node_modules
. So, a new directory appeared. All the modules needed for work have also been installed. In order to launch it, let us create the launch configuration аpp.js
; put a tick inside Single instance only
for your convinient restart. Launch it. Go to Chrome:
http://localhost:3000/
This is a port, where our app ‘listens
‘ to something, and it works.
Go back to the project now. There are a lot of things generated; to make it easier for us, let us only the vital things necessary for Express . These are:
– to connect Express,
– to create an app, which creates a function used for handling requests:
var express = require('express'); var app = express();
Further add the http
-server:
http.createServer(app).listen(app.get('port'), function(){ console.log('Express server listening on port ' + app.get('port')); });
Respectively, Express will handle all incoming requests. We will also need http
modules.
var express = require('express'); var http = require('http'); var path = require('path'); var app = express(); http.createServer(app).listen(app.get('port'), function(){ console.log('Express server listening on port ' + app.get('port')); });
Aрp.get
gets a value from a special hidden property of the object арp, which can be installed as follows (add to our app.js
):
app.set('port', 3000);
Get all the rest commented out, we do not need these things.
var express = require('express'); var http = require('http'); var path = require('path'); var app = express(); app.set('port', 3000); http.createServer(app).listen(app.get('port'), function(){ console.log('Express server listening on port ' + app.get('port')); });
Now, if we launch all these things, we will get a server listening on port 3000
and doing nothing. But why? Because the еxpress
function doesn’t handle requests by default. To make it handle them, you need to add a special handler called Middleware
in Express terms . It looks just the same as an average function, accepts req
and res
, transfers all objects and can do certain things:
// Middleware app.use(function(req, res, next) { res.end("Hello"); });
This function will respond in the same way on all requests. Launch it. Check. It works!
How does Middleware
differ from an average handler on.request
? It has the third parameter called next
. It serves to integrate Middleware
into chains. For example, you’ve got one Middleware
and do another Middleware
below. First of them checks, whether it is
if (req.url == '/') {
it calls
} else {
Otherwise, it delivers the control further:
next();
We will continue soon, please stay tuned! The lesson code can be found here.
The materials for this article have been borrowed from the following screencast.
We are looking forward to meeting you on our website soshace.com