Node.js Create a Basic Server Using Express 05

Video Tutorial

Overview

After going through on nodejs basic modules and setup, it is finally the time for creating something interesting and that is a web server using the Express Framework, also we will see and work with middlewares.

Basic Setup

First, we need to install the express framework using npm where it actually gonna help create an HTTP server also the body-parser module for parsing Form Data sent on the request

npm install express --save
npm install body-paser --save 
#Make sure to save it as a Dependency

Now create a new File server.js responsible for running our server then initialize our app and listen on a port (for ex: PORT 3000)

const express = require('express');
//Initialize the Express App
let app = express();
const port = 3000;
//Body parser 
let bodyParser = require('body-paser');

//Make sure to let the Body parser to parser our request 
app.use(
    bodyParser.urlencoded({
        extended: true
    })
);
app.use(bodyParser.json());

//and Listen on the specified Port
app.listen(port, () => {
   console.log('Server Running at port 3000');
});

Now try to run the above script using node server.js or you can add the script to the package.json in order to automate the process

//Package.json under the Script Tag
"script" : {
   "server": "node server.js"
}

Now You can just type

npm run server
#LOG: Server Running at port 3000

The server is running but actually, no routes are defined therefore using the Express Router

//Add this code Before Listening on the Port 
app.route('/').get((req, res) => {
   res.send('Hello World!');
});

Here we are specifying the route we will assign the get response to, in this case, it is the home page ( / means the domain name http://localhost:3000)) and we use a callback to send the response where it takes two parameters (request and response), you can use any sort of HTTP Requests (POST, PUT…)

Try to type http://localhost:3000 on your browser, you should get Hello World! on the page, but in most cases you don’t want to send back static text but instead HTML Files and style your pages, you can do that using the sendFile() method on the response object

const path = require('path');
sendFile(path.resolve('./index.html'));
//The method takes an absolute path, so with the help of the path module we get it to work

Now you can see your HTML file in action.

Using Middlewares

Middlewares are some function that runs on every submitted request and before sending the response back, so it can be used to parse, check or validate data by checking some header values (for ex: for API authentication we need to validate the Token) you can create middlewares for your application and on this case we will double check for a token sent with the request under the headers in order to tell whether the user has the right to access the server or no (but still this technique is not safe, if you need authentication please check JWT)

//We use the App Use method for implementing middlewares since it runs on every request 
app.use((req, res, next) => {
   //We double check for the Token if it's valid and set the auth to TRUE or FALSE 
  if(req.headers.token == 'NODEJSAPP') {
      req.auth = true
   } else {
      req.auth = false;
   }
   //pass the req to the next Handler 
   next();
});

//The Post Request or any other type
app.route('/auth').post((req, res) => {
   //We double check again
   if(req.auth)
     return res.send('OK, Authenticated');
   else 
     return res.send('Bad, You do not have the Right to access this!');
});

Since we can’t send a post request using the browser (only GET) we will use Postman Software that will help us send HTTP Requests, besides it is very nice software for API and Web Devs

Now Send a POST Request to the desired URL (localhost:3000/auth) with the headers containing our Token NODEJSAPP, you should get the Authenticated Response saying that you have been authenticated Successfully, nice isn’t it so that way you can authenticate users, but using more advanced Techniques.

So this is the basics of Web Servers, you can try to add more routes in order to truly understand how that works, but still you can’t use for more advanced operation since you still need a database to store data on (I really recommend going with MongoDB).

No Comments Yet