Newby Coder header banner

NodeJs Basic Authentication Server

Express is a Nodejs web application framework

It is used to assign routes (or paths) that are to be exposed by a server and add middlewares

Middlewares are added to a web app, so that every request passes through these middlewares allowing a number of functionalities such as request body parsing, authentication etc

Middlewares can be also imported from external packages apart from custom implementations

Some middlewares like authentication might return a response and stop further processing of a request

Middlewares can be added as generic middlewares or for specific routes

Example Express Server

Provided example sets up a nodejs express server

Requirements

Creating new Node.js Application

Create a new directory

mkdir express_test

The name of a directory should not match that of any (nodejs) dependency to be used

Change directory to newly created directory

cd express_test

Run npm init command to create a package.json file so that node packages can be installed for current package

npm init -y

-y is added so that it doesn't prompt for setting some common info about package


Dependency

Run following command from project directory

npm install express --save

Project structure

package.js is created on npm init command

Implementation

index.js - Server entry point

Save following code in index.js

// import express
const express = require('express');
// import external module to be used as middleware
const bodyParser = require('body-parser');

// declare an express app
const app = express();

// add bodyParser.json() middleware to application to parse body of each request to json
// so that any further middleware or method can access request body as json
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());

// assign a function to the route(or path) '/base', which only accepts Http Get requests (for Post request use app.post())
app.get('/base', function(req, res, next) {
    // Send a string as response, can be changed to html or json content
    res.send('Message from Express server');
});

// send a json response for route '/json'
app.get('/json', function(req, res, next) {
    // Send a json as response
    res.send({name: "test", id: 243});
});

// receives a post request and returns value of 'message' received from request body
app.post('/echo', function(req, res, next) {
    // Send the 'message' field of request body
    res.send(req.body.message);
});

// start server at port 8800
const server = app.listen(8800, function () {
    // function called after server is started
    console.log('Server listening on 8800');
});

What is next

next is a part of connect middleware

Middlewares are added as a stack

Each middleware calls next() which invokes the next middleware

Middlewares are executed one by one for each request to the app, until a middleware does not call next() within it

This flow is also stopped if next is called with an argument next(err) which is considered as an error

These can be tested to check if they behave differently, but maybe prefer altering a request req variable to send data to next middleware than trying with next(some_object)


Run instructions

Run following command from project directory

nodejs index.js

To make it as accessible over a local network such as wifi, enter local ip address with command

nodejs index.js 192.168.43.12

Here, 192.168.43.12 is ip address

Testing

Testing Get requests

Enter url in a browser to test the Apis such as http://127.0.0.1:8800/json

cl-express-server-string-responsecl-express-server-json-response

Testing Post request using html file

Save following code in a file named test.html (or some other name with .html extension) in a directory

Replace url in case server is run in some ip address other that localhost

Open the file in a browser (double-click should do that)

<!doctype html>
<html>
  <meta charset="utf-8">
  <body>
    <div>
      <div>
      <h3>Test echo</h3>
      <form action="http://127.0.0.1:8800/echo" method="post">
        <table>
          <tr>
            <td><label for="id_message">Enter some text</label></td>
            <td><input type="text" id="id_message" name="message"></td>
          </tr>
          <tr>
            <td></td>
            <td><input type="submit" value="submit"></td>
          </tr>
        </table>
      </form>
    </div>
  </body>
</html>
cl-express-server-post-request