Express Framework: Simple guide in Node.js for the beginners

express framework

What do you know about Node.js? It’s an impressive platform that many huge brands use such as PayPal, Netflix, LinkedIn, eBay, NASA,… But do you know which component is the most important in Node.js? It is Express Framework!

In this article, ArrowHiTech will deliver a detailed guidance on Express Framework, especially for beginners. If you have any comments or questions, feel free to do it!

The ideas that we’re covering today are:

  • Definition
  • Benefits
  • Installation
  • Functions

Let’s get started!

What is Express?

Express is a flexible framework for Node.js. What’s more, it comes with a wide range of effective features to create and develop web or mobile apps. Some core Express features are:

  • Set up middlewares to respond to HTTP requests
  • Define routing tables to perform on HTTP method and URL
  • Render HTML pages by passing arguments to templates
express framework example
Popular brands that use Node.js

Is Express Framework important?

When comparing Express Framework over some normal Node.js, you can see there’s a big gap. Firstly, Express is much easier to use and more effective to create web apps and services. Secondly, Express provides consistent Routing to modules and Middleware interface. Lastly, it can productively handle post data, manage sessions and serve static files,…

Want to install it now? Just follow these simple steps:

How to install?

Before installing Express, you need to install Node.js first. Click this official link from Node.js to download packages. Then using NPM to install Express framework like this command:

$ npm install express --save

Moreover, along with Express, you should also install these essential modules:

  • Body-parser: handle JSON, Raw,Text and URL
  • Cookie-parser: populate req.cookies with an object
  • Multer: handle multipart or multiform data

Run this command to download them:

$ npm install body-parser --save
$ npm install cookie-parser --save
$ npm install multer --save

How does Express work?

In this part of the article, we will mainly show ways to perform action within Express by some sorts of coding.

1. Router Module

Express framework router module is used to separate routes of a specific app. First, create route.js in root directory:

const express = require('express');
const router = express.Router();
// define the home page route
router.get('/', function (req, res) {
  res.send('This is the Home Page');
});
// define the contact route
router.get('/contact', function (req, res) {
  res.send('Contact Page Information');
});
module.exports = router;

Then, create another app.js file which is the starting file for your app:

const express = require('express');
let app = express();
const route  = require('./route');
app.use('/', route);
app.listen(3000, function () {
    console.log('app is running on port 3000');
});

To start or visit app, following this command:

  • start the app: node app.js
  • visit home page: localhost:3000/
  • visit contact page: localhost:3000/contact

2. Body Parser Implementation

As we have mentioned, body-parser help handle HTTP Post requests. To install Body-parser: npm install body-parser --save

Then, to implement it in Express Framework:

const express = require('express'),
      app = express(),
      bodyParser = require('body-parser');

// support parsing of application/json type post data
app.use(bodyParser.json());

//support parsing of application/x-www-form-urlencoded post data
app.use(bodyParser.urlencoded({ extended: true }));

3. Static Files

In Express, this middleware can serve statice files namely images, CSS, JavaScript, etc. For example, if you want to keep all images, CSS and JavaScript files in a file named ‘data’, do as follow:

app.use(express.static('data'));
node_modules
server.js
data/
data/images
data/images/logo.png

Very simple, isn’t it?

express framework static file
Serving Static Files is not difficult at all!

4. GET Method

In short, we use process_get router to handle input.

<html>
   <body>
      
      <form action = "http://127.0.0.1:8081/process_get" method = "GET">
         First Name: <input type = "text" name = "first_name">  <br>
         Last Name: <input type = "text" name = "last_name">
         <input type = "submit" value = "Submit">
      </form>
      
   </body>
</html>

Now, save the code in index.htm. Then, change server.js to handle hom page requests as follow:

var express = require('express');
var app = express();

app.use(express.static('public'));
app.get('/index.htm', function (req, res) {
   res.sendFile( __dirname + "/" + "index.htm" );
})

app.get('/process_get', function (req, res) {
   // Prepare output in JSON format
   response = {
      first_name:req.query.first_name,
      last_name:req.query.last_name
   };
   console.log(response);
   res.end(JSON.stringify(response));
})

var server = app.listen(8081, function () {
   var host = server.address().address
   var port = server.address().port
   
   console.log("Example app listening at http://%s:%s", host, port)
})

A link called http://127.0.0.1:8081/index.htm will generate a form that includes first and last name. Lastly, after hitting submit, let’s take ArrowHiTech for instance, it will lead to:

{"first_name":"HiTech","last_name":"Arrow"}
express framework node

5. POST Method

Similar to GET method, we also use process_get:

<html>
   <body>
      
      <form action = "http://127.0.0.1:8081/process_post" method = "POST">
         First Name: <input type = "text" name = "first_name"> <br>
         Last Name: <input type = "text" name = "last_name">
         <input type = "submit" value = "Submit">
      </form>
      
   </body>
</html>

The following final steps are pretty much the same, so we will just put out the code here:

var express = require('express');
var app = express();
var bodyParser = require('body-parser');

// Create application/x-www-form-urlencoded parser
var urlencodedParser = bodyParser.urlencoded({ extended: false })

app.use(express.static('public'));
app.get('/index.htm', function (req, res) {
   res.sendFile( __dirname + "/" + "index.htm" );
})

app.post('/process_post', urlencodedParser, function (req, res) {
   // Prepare output in JSON format
   response = {
      first_name:req.body.first_name,
      last_name:req.body.last_name
   };
   console.log(response);
   res.end(JSON.stringify(response));
})

var server = app.listen(8081, function () {
   var host = server.address().address
   var port = server.address().port
   
   console.log("Example app listening at http://%s:%s", host, port)
})

6. File Upload

Use this HTML code to create a form of file uploader:

<html>
   <head>
      <title>File Uploading Form</title>
   </head>

   <body>
      <h3>File Upload:</h3>
      Select a file to upload: <br />
      
      <form action = "http://127.0.0.1:8081/file_upload" method = "POST" 
         enctype = "multipart/form-data">
         <input type="file" name="file" size="50" />
         <br />
         <input type = "submit" value = "Upload File" />
      </form>
      
   </body>
</html>

Then, save above code in index.htm and change server.js to handle home page requests. As a matter of fact, these steps are pretty much the same as GET method, so we just go over it quickly:

var express = require('express');
var app = express();
var fs = require("fs");

var bodyParser = require('body-parser');
var multer  = require('multer');

app.use(express.static('public'));
app.use(bodyParser.urlencoded({ extended: false }));
app.use(multer({ dest: '/tmp/'}));

app.get('/index.htm', function (req, res) {
   res.sendFile( __dirname + "/" + "index.htm" );
})

app.post('/file_upload', function (req, res) {
   console.log(req.files.file.name);
   console.log(req.files.file.path);
   console.log(req.files.file.type);
   var file = __dirname + "/" + req.files.file.name;
   
   fs.readFile( req.files.file.path, function (err, data) {
      fs.writeFile(file, data, function (err) {
         if( err ) {
            console.log( err );
            } else {
               response = {
                  message:'File uploaded successfully',
                  filename:req.files.file.name
               };
            }
         
         console.log( response );
         res.end( JSON.stringify( response ) );
      });
   });
})

var server = app.listen(8081, function () {
   var host = server.address().address
   var port = server.address().port
   
   console.log("Example app listening at http://%s:%s", host, port)
})
nodejs

Lastly, using http://127.0.0.1:8081/index.htm  will generate a form for you to choose and upload the files.

In Express Framework, cookies are sent to a Node.js server that optimize this middleware option. For example, if you want to print the cookies that clients send, use this following command:

var express      = require('express')
var cookieParser = require('cookie-parser')

var app = express()
app.use(cookieParser())

app.get('/', function(req, res) {
   console.log("Cookies: ", req.cookies)
})
app.listen(8081)

That’s all for today’s topic! If you want to read more about Node.js, check out these helpful guides and articles about:

Need help with Express Framework? Contact us RIGHT NOW!

If you still have trouble learning Express Framework for Node.js apps, why not hiring experts? It is a very wise investment, which leads to time saving, cost effectiveness and outstanding results. ArrowHiTech is proud to be one of the leading IT Outsourcing agencies in Vietnam.

With over 13 years in the industries, satisfying more than 10,000 clients globally, we are confident that your issues will be solved in no time! Our services and solutions are fast, low cost and always bring a smile to all clients’ face! You can check out our portfolio as well as our Node JS Development Services for more details!

Bottom Line

Today, we have delivered an article on Node.js Express Framework. ArrowHiTech hopes that you find it helpful for your journey.

And as always, we truly wish the best of luck and success will come to you! WE’D LOVE TO HEAR FROM YOU AT:

Tags

Share