• Translate

7/06/2017

Web Application Creation Tutorial with Express.js (Part 1): Installation and Introduction

Tutorial Web Design |

Advertisement

Express.js is the world's most popular web framework Node.js Complete documentation and easy-to-use usage, can make us develop various products such as web application or RESTful API. Express.js can also be used as a foothold for building more complex web frameworks such as, Sails.js, MEAN (MongoDB, Express.js, Angular.js, Node.js) and MERN (MongoDB, Express.js, React.js, Node.js). Express.js was created by TJ Holowaychuk and is now managed by the community.

Some of the advantages possessed by Express.js include:
  • Support middleware creation
  • Support for various HTTP verbs such as POST, GET, PUT, DELETE, OPTION, HEAD, and more
  • Already installed Jade template engine
  • Static file management such as CSS and Javascript
  • Very free to customize
In this first part of the tutorial, you'll get to know how we use the most basic Express.js and basic techniques we'll learn to build a web app. Enjoy this tutorial.

Installation

To use Express.js, make sure you install Node.js first and make sure the NPM is working. This tutorial is created using Node.js version 5.10.1 and NPM version 3.8.5. Via console or terminal please execute the following command. Make sure select the folder you like:
$ npm install express -g
$ express demo
$ npm install
$ npm start
Now let's look at the first page generated by Express.js in the web browser. Please access the URL http://localhost:3000/, the form will be like this: 
http://localhost:3000/

Folder Structure Express.js

When first created, Express.js has a folder structure like the following:
  • bin, in which there is a file named www where the file will be executed when running the command "npm start"
  • node_modules, in which there are various folders of Node.js libraries installed through the node package manager or NPM
  • public, we can put various CSS files, Javascript, or images inside this folder.
  • routes, in which there are various files containing the actions received by the routing that we define. Can accept requests in the form of GET, POST, PUT, DELETE, OPTION, and HEAD
  • views, in which there are various jade or html files used by routes to display the page
  • app.js, Express.js main file containing the use of the main package and main configuration
  • npm-debug.log, a file containing the debug or error results Express.js records during running
  • package.json, contains the JSON structure that defines the project profile and what package dependencies the application needs we develop. NPM will track dependencies by viewing this file.

 

Important File Express.js

Now let's take a look at the sample file contents app.js. In it you will see the use of certain libraries by using require() and then install it in Express.js using use(), then to set the global variable used set()
var express = require('express');
var path = require('path');
var favicon = require('serve-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');

// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use('/', routes);
app.use('/users', users);

// catch 404 and forward 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;
Next, take a look at the contents of the package.json file in which there is a configuration file which will be executed by "npm start", then there is also a list of dependencies used by the application we developed along with its version: 
{
  "name": "demo",
  "version": "0.0.0",
  "private": true,
  "scripts": {
    "start": "node ./bin/www"
  },
  "dependencies": {
    "body-parser": "~1.13.2",
    "cookie-parser": "~1.3.5",
    "debug": "~2.2.0",
    "express": "~4.13.1",
    "jade": "~1.11.0",
    "morgan": "~1.6.1",
    "serve-favicon": "~2.3.0"
  }
}
The bin/www file contains the code to run the application with the default port and configure other information at runtime: 
#!/usr/bin/env node

/**
 * Module dependencies.
 */

var app = require('../app');
var debug = require('debug')('demo:server');
var http = require('http');

/**
 * Get port from environment and store in Express.
 */

var port = normalizePort(process.env.PORT || '3000');
app.set('port', port);

/**
 * Create HTTP server.
 */

var server = http.createServer(app);

/**
 * Listen on provided port, on all network interfaces.
 */

server.listen(port);
server.on('error', onError);
server.on('listening', onListening);

/**
 * Normalize a port into a number, string, or false.
 */

function normalizePort(val) {
  var port = parseInt(val, 10);

  if (isNaN(port)) {
    // named pipe
    return val;
  }

  if (port >= 0) {
    // port number
    return port;
  }

  return false;
}

/**
 * Event listener for HTTP server "error" event.
 */

function onError(error) {
  if (error.syscall !== 'listen') {
    throw error;
  }

  var bind = typeof port === 'string'
    ? 'Pipe ' + port
    : 'Port ' + port;

  // handle specific listen errors with friendly messages
  switch (error.code) {
    case 'EACCES':
      console.error(bind + ' requires elevated privileges');
      process.exit(1);
      break;
    case 'EADDRINUSE':
      console.error(bind + ' is already in use');
      process.exit(1);
      break;
    default:
      throw error;
  }
}

/**
 * Event listener for HTTP server "listening" event.
 */

function onListening() {
  var addr = server.address();
  var bind = typeof addr === 'string'
    ? 'pipe ' + addr
    : 'port ' + addr.port;
  debug('Listening on ' + bind);
}

 

Getting to Know the Jade Engine Templates

Suppose we find a file called layout.jade:
doctype html
html
  head
    title= title
    link(rel='stylesheet', href='/stylesheets/style.css')
  body
    block content
Then the layout is used by index.jade:
extends layout

block content
  h1= title
  p Welcome to #{title}
So if we imagine, the result will be like this but without having to retype certain parts in different files that use layout.jade
doctype html
html
  head
    title= title
    link(rel='stylesheet', href='/stylesheets/style.css')
  body
    h1= title
    p Welcome to #{title}
Templating using Jade may be rather strange and unusual, since we do not use HTML tag cover or opening. To state that an element is within another element, we first give one tab under the element which will contain another element. Then there is the extends and block syntax which means that we use template layout.jade as container for index.jade. Then Jade will look for block content position and fill it with elements in index.jade.

In addition to printing the variable we use the syntax #{variable_name}. As for using the HTML attribute on an element, we use the "("and")" marks by filling in the attributes to be used. For example let's look at the following example: 
//example 1
html:

<h1>Hello World</h1>

jade:

h1 Hello World

//example 2
html:

<table id="table-mahasiswa" class="table table-hovered" border="1" style="display:inline-block;padding:50px;">
    <tbody>
        <tr>
            <td>1</td>
            <td>hello</td>
            <td>world</td>
        </tr>
    </tbody>
</table>

jade:

table(border="1", style="display:inline-block;padding:50px;")#table-mahasiswa.table.table-hovered
    tbody
        tr
            td 1
            td hello
            td world
To facilitate the creation of Jade files, you can use the http://html2jade.com converter but of course the conversion results should be checked first, because Jade is very sensitive to differences in the use of spaces and tabs. Jade requires that we only use one type of tab whether using only spaces or tabs. Should not be mixed. 

 

Routing in Express.js

Now we try to open the index.js file in the routes folder:
var express = require('express');
var router = express.Router();

/* DEMO 0 - halaman index */
router.get('/', function(req, res, next) {
  res.render('index', { title: 'Express' });
});

module.exports = router;
You can see in each file routes must use Express.js module first, then create the instance of Router() and then we can define what URL then handled by what action. The actions we miss into routes must accept request, response, and next variables. You can display the Jade templates in the views folder by using the render() that belongs to the response object. In the above code, the response object is captured by the res parameter, then we call render() via res.render() and then specify which *Jade file we will show, and we can skip some variables with the "{" and " }".

For this route, the index.jade file will be displayed and assigned a value of title containing "Express": 
extends layout

block content
  h1= title
  p Welcome to #{title}
When we access url http://localhost:3000/ it will appear the following view:
Welcome Title on http://localhost:3000/

Sending Variables to Templates

Still in the index.js file. Now we try to add the parameters passed to a template named demo1.jade. We will pass a message named message and an object named user:
/* DEMO 1 - render template */
router.get('/demo1', function(req, res, next) {
  res.render(
                'demo1',
                {
                    message: 'Lorem ipsum sit dolor amet',
                    user: {name:'suyono', email:'suyono@example.com', website: 'http://www.suyono.com'}
                }
            );
});
As you can see, we miss two variables and user variables have a more detailed structure in them. When we will show in demo1.jade then the code will be as follows: 
extends layout

block content
  p message: #{message}
  p user.name: #{user.name}
  p user.email: #{user.email}
  p user.website: #{user.website}
When we access url http://localhost:3000/ demo1 it will appear the following view: 
Sending Variables to Templates

Accepting URL Parameters

Still in the index.js file. Now we try again another important technique. We will use URL parameters in a route. To indicate that a segment is a parameter we must bracket it with the "(:" and ")" sign then write the parameter name. To catch it inside the code, you can call req.params.name_variabel according to the parameter name specified:
/* DEMO 2 - parameter in URL */
router.get('/demo2/(:id)/(:category)', function (req, res, next){
    res.render('demo2',
                        {
                            id: req.params.id,
                            category: req.params.category,
                        }
                );
});
Now we will show in demo2.jade file. Create the file in the views folder: 
extends layout

block content
  p id: #{id}
  p category: #{category}
When we access url http://localhost:3000/demo2/1/food then the following display will appear: 
Accepting URL Parameters

Showing JSON Response

Still in the index.js file. Not much different from displaying a template file. Now we will show directly a Javascript object and display it as a JSON response using json():
/* DEMO 3 - displays the response JSON */
router.get('/demo3', function(req, res, next) {
  res.json({
                message: 'Lorem ipsum sit dolor amet',
                user: {name:'maulana', email:'maulana@example.com', website: 'http://www.alltutorials.info'}
        });
});
When we access the url http://localhost:3000/demo3 it will display the following: 
Showing JSON Response

Accept Request POST

Still in the index.js file. Now we will try to display a form and send it via POST method. First we create a route to first display the form. Then create a route to catch completed POST submission:
/* DEMO 4 - receive POST request method from form */
router.get('/demo4/', function (req, res, next){
  res.render('demo4');
});

router.post('/demo4/', function (req, res, next){
  res.json(
            {
              message: "request POST is executed",
              data: {
                username: req.param('username'),
                email: req.param('email'),
                website: req.param('website'),
                phone: req.param('phone'),
              }
            }
        );
});
In the above code, to capture the results of the POST post, we use req.param ('variable_name'), unlike how to capture GET submissions where we call req.params.name_variables. Be careful not to be confused.

Now we try to make its form by using Jade template. Please create a file with the name demo4.jade in the views folder: 
extends layout

block content
    h3 Demo Form
    form(action='/demo4', method='post')
        input(type='text', name='username', placeholder='username')
        br
        br
        input(type='text', name='email', placeholder='email')
        br
        br
        input(type='text', name='website', placeholder='website')
        br
        br
        input(type='text', name='phone', placeholder='phone')
        br
        br
        input(type='submit', value='Submit')
When we access url http://localhost:3000/demo4 it will display the following:
Accept Request POST

Accept Request POST

Accept Request PUT

Unlike POST and GET, we will try the PUT method in Express.js, this method can only be captured by requests that require the PUT method. So when accessed directly from the web browser will be difficult to do because there is no support for this method. However we can use Curl or Postman to try to access routes that are PUT coded. This method is commonly used to build RESTful API.

Now let's create a route with URL/demo5 which will display a JSON sent by the client:
/* DEMO 5 - accepts request method PUT */
router.put('/demo5/', function (req, res, next){
  res.json(
            {
              message: "request PUT is executed",
              data: {
                username: req.param('username'),
                email: req.param('email'),
                website: req.param('website'),
                phone: req.param('phone'),
              }
            }
        );
});
If we use POSTMAN to access the route it will appear response as in the picture:
Accept Request PUT

Accept Request DELETE

We will work on this section in the index.js file. Almost the same as PUT, DELETE is currently not supported by the web browser. We will create a route with DELETE and have URL/demo6 which will display a JSON response:
/* DEMO 6 - accept request method DELETE */
router.delete('/demo6/', function (req, res, next){
  res.json(
            {
              message: "request DELETE is executed"
            }
        );
});
If we use POSTMAN to access the route it will appear response as in the picture:
Accept Request DELETE

Redirect to another URL

Still in the same file, the redirect process is of course needed when we have done a process, want to be returned to the original page or to a specific page. We will create a route with URL/demo7 which will redirect by using res.redirect() to URL/demo7_result:
/* DEMO 7 - redirect url */
router.get('/demo7', function (req, res, next){
    res.redirect('/demo7_result');
});

router.get('/demo7_result', function (req, res, next){
    res.render('demo7');
});
Here are views from URL /demo7_result. Please create the following template with demo7.jade name and save it in the views folder: 
Extends layout

Block content
   P Result redirect from /demo7
When we access the url http://localhost:3000/Demo7 it will display the following: 
Redirect to another URL

Closing

As a prefix, hopefully this tutorial can be quite understandable to proceed to the next Express.js tutorial that will get to know more in how to create web applications with Express.js and MongoDB. To learn about Node.js and Express.js, you need a high will and have to find your own resources. Because there are still a few colleges or vocational schools that want to teach Node.js or Express.js. May be useful.

Cooperation with (codepolitan / expressjs / nodejs)

Disqus
Blogger
Comment
How to style text in Disqus comments Top Disqus Commentators
  • To write a bold letter please use <strong></strong> or <b></b>.
  • To write a italic letter please use <em></em> or <i></i>.
  • To write a underline letter please use <u></u>.
  • To write a strikethrought letter please use <strike></strike>.
  • To write HTML code, please use <code></code> or <pre></pre> or <pre><code></code></pre>, and please parse the code in the parser box below.
Show Parser Box

No comments Add Comment

Comments not appropriate topic will sign SPAM.