How to create express-routes using controllers


Express is a Nodejs frame work which can be used to create web applications. A route represents a page in the web app or website. An ideal express app consist of multiple web pages.

Prerequisites

We need the following before proceeding to the next step

  • Nodejs, install the Node
  • A Code editor of your choice ( sublimText/Atom/VS-Code)
  • A browser

For simple project we can put all of them inside a single file such as inex.js but it is a good practice to modularize the project with folder and files. So that it help manage the project easily.

The Folder structure

Following are the folder structure for the express project. First create project folder using command prompt or you can use the code editors command

In Atom you can use Shit +A for new folder , A for new file

Project Folder Structure
md express-route
cd express-route
md app
cd app
md controllers

Generate package file for the project with start script. We can use the npm init command for this purpose.

npm init -y 

by default init command will ask you a series of question , we can avoid them and use default values using the -y option.

Also add a start script to the pacjage.json file as follows

  "scripts": {
   "test": "echo \"Error: no test specified\" && exit 1",
   "start": "node index.js"
},

Create index,controller,routes files

Index.js : This file is the starting point of our project, create a new files with .js under the Project folder

controller.js : controllers hold the definition for the different routes ( Save under the controllers folder)

routes.js : This file where we declare all our express-routes and later use them in index.js (Save under the app folder)

Install the Express

Lets install essential packages for our project , on the shell please issue the following ( make sure you have internet connection)

npm install express --save

Define the controllers

The controller function is a simple java script module consisting of the following (in the file controllers.js)

module.exports = {
home:(req,res)=>{
  try {
    res.status(200).send('This is a Home Page')
  } catch (e) {
    console.log(e);
  }
},
about:(req,res)=>{
  try {
    res.status(200).send('This is a About Page')
  } catch (e) {
    console.log(e);
  }
},
contact:(req,res)=>{
  try {
    res.status(200).send('This is a Contact Page')
  } catch (e) {
    console.log(e);
  }
},
}

Prepare the routes

Let’s create our express-routes using the controller functions ( in the file app/routes.js )

const express = require('express');
const router = new express.Router;
const Controllers = require('./Controllers/Controllers')

router.get('/',Controllers.home)
router.get('/about',Controllers.about)
router.get('/contact',Controllers.contact)

module.exports = router;

Using express-router module we define the routes for our app and also import and utilized the controller functions and finally exported the module and get things ready for the routes in the index.js

Setup server, routes

The final step is to create use the routes and start our Node server (localhost). Now the index.js will look like

const express= require('express')
const app=express()
//routes
app.use(require('./app/routes'))

app.listen(3000, () => console.log('server on!'));

Here we had imported the routes.js as middle ware and will cause implementing all the routes defined in the routes.js file

Run the server

We can run the project using the start script configured in the package file.

npm start

and in the console the server on message will shown. Got to your browser and lunch the app using http://localhist:3000 and also try /about/ and /contact routes.

How to add data on MongoDB using Node-Express API


In this tutorial we are going to do two important things

  • Create an API which is capable of perform CURD operation on MongoDB server
  • User the API to perform CURD in a web app

Making of the API

MongoDB is NoSQL database which is capable of running on the cloud and local alike.

  • How to create an API using Express in Nodejs

    API is an essential part of modern apps and web applications, it allow users to perform CURD operations using one single web interface. An identical API uses JSON structure to store and retrieve data. It is suitable for mobile app or another web app.

    One of the advantage of API is that it can be utilized by multiple applications. It also mean that the CURD operation need not be write again again and again in each applications.

    Not sure where to start learning ?, check out these Node tutorials

    API

    Let’s create a simple API using

    • Express
    • Joi
    • Nodejs

    Express

    Express help us create and manage web app pages or routes, it is the simplest way to create a web app in Nodejs. Many other NodeJS frameworks are build up on Express as the root.

    JOI

    JOI is a NPM package which help us create a schema for our API and validate.

    The source code

    const Joi = require("joi");
    const express = require("express");
    const app = express();

    app.use(express.json());
    const courses = [
    { id: 1, name: "course 1" },
    { id: 2, name: "course 2" },
    { id: 3, name: "course 3" },
    ];
    app.get("/", (req, res) => {
     res.send("Hello world");
    });

    app.get("/api/courses", (req, res) => {
     res.send(courses);
    });

    app.post("/api/courses", (req, res) => {
     const schema = {
       name: Joi.string().min(3).required(),
    };

     const result = Joi.validate(req.body, schema);
     if (result.error) {
       res.status(404).send(result.error.details[0].message);
       return;
    }
     const course = {
       id: courses.length + 1,
       name: req.body.name,
    };

     courses.push(course);
     res.send(course);
    });

    app.delete("/api/courses/:id", (req, res) => {
       const course = courses.find((c) => c.id === parseInt(req.params.id));
       if (!course)
           return res.status(404).send("The course not found");
           
     
       const index= courses.indexOf(course)
       courses.splice(index,1)    
       res.send(course)
    });

    function validateCourse(course) {
     const schema = {
       name: Joi.string().min(3).required(),
    };

     return Joi.validate(course, schema);
    }
    app.get("/api/courses/:id", (req, res) => {
     const course = courses.find((c) => c.id === parseInt(req.params.id));
     if (!course) res.status(404).send("The course not found");
     res.send(course);
    });

    const port = process.env.PORT || 3000;
    app.listen(port, () => {
     console.log(`listen on the port ${port}`);
    });

    The app has 5 APIs to perform CURD operations, as you noticed that all API routes are organized in the /api/ route which is a common standard. A secure API also uses a security key to access the data.

    The API add,remove,delete,update courses. For update the data I used PUT method which is actually update all the data. .An alternative to this is a PATHCH which update one only one

    The Slice method is used to remove data from the collection, Push is used to add a new data and find will fetch data from the JSON collection.

    How to run and Test API

    As you may noticed that this app don’t have UI for operations. API usually lack , because they are meant for developers and not to all users, so UI is less important. In order to test the API you should have Postman Like application, where you can test POST,GET,PUT APIs. Postman can be used for free, all you need to register and download the desk app for your plat form.

    In the New / Next to Launch Pad you can create, test new request and in the Body – > raw you can use JSON data.

$(function () {
// code block here
}

HTML Web app

In the HTML file very last line of the body (</body>) tag include the script as follows, also you need to include the CDN version or local version of jQuery library.

  <script src="/jquery.js"></script>  -- local version of jQuery library
  <script src="/public/script.js"></script>  -- our script

jQuery

jQuery can be placed in a file or with in HTML within <script> </script > , I used to store them as file for easy access. It is a good practice include it in a document ready function, so that we can make sure the query will only execute only when the web page loading completed.

Using the API – GET and POST request

The GET request is used to get a list of data, says product list,users list, customer list etc and the POST send data to the server. By default API call will make GET request

POST API Call using jQuery and AJAX


With JQuery ( light weight, super Java Script library) we can handle events, dynamically add content to html blocks.

Let’s learn how to make a POST API request in HTML/web app using jQuery and AJAX? POST request used to send data to the server.

jQuery

jQuery can be placed in a file or with in HTML within <script> </script > , I used to store them as file for easy access. It is a good practice include it in a document ready function, so that we can make sure the query will only execute only when the web page loading completed.

$(function () {
// code block here
}

HTML

In the HTML file very last line of the body (</body>) tag include the script as follows, also you need to include the CDN version or local version of jQuery library.

  <script src="/jquery.js"></script>  -- local version of jQuery library
  <script src="/public/script.js"></script>  -- our script

How to make POST API request

In this example we are about to add data into the server using API POST method.

The GET request is used to get a list of data, says product list,users list, customer list etc and the POST send data to the server. By default API call will make GET request

In the script file you can add following code to access the API, in our example it is a list of users

 $("#submit-btn").on("click", function () {
    var inputUname = $("#input-uname");
    var inputEmail = $("#input-email");
    var inputPass = $("#input-passwd");
  
    $.ajax({
      url: "/api/user",
      method: "POST",
      contentType: "application/json",
      data: JSON.stringify({
        uname: inputUname.val().trim(),
        email: inputEmail.val().trim(),
        pass: inputPass.val().trim(),
      }),
      success: (response) => {
        alert("New user created");
        inputUname.val("");
        inputEmail.val("");
        inputPass.val("");
        $("#btn-get").click();
      },
      error: (err) => {
        alert("Please fill the boxes");
      },
    });
  });

the AJAX call is made inside the document ready function, which will execute only after the complete web page is loaded. The ajax call has following properties

  • url – the API itself
  • contentType – type of the content , it can be json structured in many cases.
  • method – POST/GET
  • data – a JSON data to the server
  • Success – function that will execute after the call made successfully
  • error : – can be arrow function for handling errors

The success function return a response , in which our retiring data is packed. In this example the new user object.

Some jQuery post will help you to extend the functionality of your app.

GET API Call using jQuery and AJAX


With JQuery ( light weight, super Java Script library) we can handle events, dynamically add content to html blocks.

Let’s learn how to make a GET API request in HTML/web app using jQuery and AJAX?

jQuery

jQuery can be placed in a file or with in HTML within <script> </script > , I used to store them as file for easy access. It is a good practice include it in a document ready function, so that we can make sure the query will only execute only when the web page loading completed.

$(function () {
// code block here
}

HTML

In the HTML file very last line of the body (</body>) tag include the script as follows, also you need to include the CDN version or local version of jQuery library.

  <script src="/jquery.js"></script>  -- local version of jQuery library
  <script src="/public/script.js"></script>  -- our script

How to make GET API request

We have learned how create an API and test API with Post Man client. if you miss the post here it is.

We need to access the API in the real world applications. We can use JavaScript for web apps for that and the best way to do is using jQuery and AJAX.

The GET request is used to get a list of data, says product list,users list, customer list etc and the POST send data to the server.

In the script file you can add following code to access the API, in our example it is a list of users

$(function () {
 $("#btn-get").on("click", function () {
   //List users using API with AJAX

   $.ajax({
     url: "/api/user",
     contentType: "application/json",
     success: function (response) {
       // console.log('success');
       var el = $("#usr-group");
       el.html("");
       response.users.forEach(function (usr) {
         el.append('<li class="list-group-item">' + usr.uname + "</li>");
      });
    },
  });
});
});

the AJAX call is made inside the document ready function, which will execute only after the complete web page is loaded. The ajax call has following properties

  • url – the API itself
  • contentType – type of the content , it can be json structured in many cases.
  • Success – function that will excecuted after the call made successfully
  • error : – can be arrow function for handling errors

The success function return a response , in which our data is packed. In this example the users object. we can iterate through the object list and add to the webpage using jQuery.

Some jQuery post will help you to extend the functionality of your app.

How to create animated tool tip container with CSS and jQuery


With JQuery ( light weight, super Java Script library) we can handle events, dynamically add content to html blocks.

Let’s learn to create custom tool-tip container with CSS and jQuery?

jQuery

jQuery can be placed in a file or with in HTML within <script> </script > , I used to store them as file for easy access. It is a good practice include it in a document ready function, so that we can make sure the query will only execute only when the web page loading completed.

$(function () {
// code block here
}

HTML

In the HTML file very last line of the body (</body>) tag include the script as follows, also you need to include the CDN version or local version of jQuery library.

  <script src="/jquery.js"></script>  -- local version of jQuery library
  <script src="/public/script.js"></script>  -- our script

and the container look like the following (HTML)

 <section class="tool-tip-hide alert text-info" id="ask-tool-tip">            
                   </section>

CSS

Here is our CSS code to hide and show the container

.tool-tip-hide{
    display: none;
}
.tool-tip-show{
    display:inline     ;
}

jQuery code

 $(function () {
  
  var info = $("#ask-tool-tip");
  function resetTooltip() {
    info.removeClass("tool-tip-show");
    info.addClass("tool-tip-hide");
    info.html('')
  }

  resetTooltip();

 async function Message(msg) {
    resetTooltip();
    info.html("");
    info.append(`<i>${msg} !</i>`);
    info.removeClass("tool-tip-hide");
    info.addClass("tool-tip-show").fadeOut(3000, () => {
        info.fadeIn()
  
    });
  
  }
$("#btn-click").on("click", () => {
 Message("Thank you");
})

}

In the above jQuery we are done the following

  • locate the container adding class to the HTML ( tool-tip-hide)
  • create custom method for setup message with animation
  • call the Message function inside a event handler

How to add/remove CSS class using jQuery


With JQuery ( light weight, super Java Script library) we can handle events, dynamically add content to html blocks.

Let’s learn change visual UI features by adding/removing CSS class from jQuery?

jQuery

jQuery can be placed in a file or with in HTML within <script> </script > , I used to store them as file for easy access. It is a good practice include it in a document ready function, so that we can make sure the query will only execute only when the web page loading completed.

$(function () {
// code block here
}

HTML

In the HTML file very last line of the body (</body>) tag include the script as follows, also you need to include the CDN version or local version of jQuery library.

  <script src="/jquery.js"></script>  -- local version of jQuery library
  <script src="/public/script.js"></script>  -- our script

Add or Remove CSS class

jQuery has capability of adding and removing properties of DOM elements such as class. It will be help us to change the visual appearance of the container according to user interations

   el.addClass('class-name')
   el.removeClass('class-name')
  

using el.find() can check for the the existence of the class

How to show/hide DOM element using jQuery


With JQuery ( light weight, super Java Script library) we can handle events, dynamically add content to html blocks.

Let’s learn how to show and Hide a div with JQuery

jQuery

jQuery can be placed in a file or with in HTML within <script> </script > , I used to store them as file for easy access. It is a good practice include it in a document ready function, so that we can make sure the query will only execute only when the web page loading completed.

$(function () {
 
}

HTML

In the HTML file very last line of the body (</body>) tag include the script as follows, also you need to include the CDN version or local version of jQuery library.

  <script src="/jquery.js"></script>  -- local version of jQuery library
  <script src="/public/script.js"></script>  -- our script

Show and Hide action

   $("#show-btn").on("click", function () {
 var el=$('#element')
 el.show().fadeIn(1000)
}
  $("#hide-btn").on("click", function () {
 var el=$('#element')
 el.hide().fadeIn(1000)
}

By using the id of the div we access the element and call the show/hide method. We can add cool animation with jQuery too.

How to redirect a page in jQuery


With JQuery ( light weight, super Java Script library) we can handle events, dynamically add content to html blocks. Let’s learn how to redirect to a webpage or route in jQuery?

jQuery

jQuery can be placed in a file or with in HTML within <script> </script > , I used to store them as file for easy access. It is a good practice include it in a document ready function, so that we can make sure the query will only execute only when the web page loading completed.

$(function () {
// code block here
}

HTML

In the HTML file very last line of the body (</body>) tag include the script as follows, also you need to include the CDN version or local version of jQuery library.

  <script src="/jquery.js"></script>  -- local version of jQuery library
  <script src="/public/script.js"></script>  -- our script

Redirecting the page

Using the Window.location we can redirect to another webpage or route as follows

   
 window.location.href = "/home.html";

The href can be a web page or an external link . The following post may help you to explore jQuery

How to load content into div using jQuery


With JQuery ( light weight, super Java Script library) we can handle events, dynamically add content to html blocks. Let’s learn how to add content to div using class id/class

jQuery

jQuery can be placed in a file or with in HTML , I used to store them as file for easy access. It is a good practice include it in a document ready function, so that we can make sure the query will only execute only when the web page loading completed.

$(function () {
// code block here
}

HTML

In the HTML file very last line of the body (</body>) tag include the script as follows, also you need to include the CDN version or local version of jQuery library.

  <script src="/jquery.js"></script>  -- local version of jQuery library
  <script src="/public/script.js"></script>  -- our script

Adding the content

Adding the content to a div can be achieved

  • access the DOM element using id
  • Placing content using one of the following method
  1. append() – Inserts content at the end of the selected elements
  2. prepend() – Inserts content at the beginning of the selected elements
  3. after() – Inserts content after the selected elements
  4. before() – Inserts content before the selected elements

Here is the plan

  • Find the element using jQery function
  • Clear the content
  • Append the content
$(function () {
  var divEl=$("#content-area")
  divEl.htm('')
  divEl.appen('<p>I am a paragraph</p>')
});

Here the divEl.html(”) is used to clear the content. We can also use class to access the element in a HTML file by using $(‘className’)

I recommend the following post for further read

flask-gentelella : A beautiful admin bootstrap for pythoners


Gentelella is a free to use bootstrap admin template for developing Python Flask web app, with custom Ajax libraries which includes variety of chart scripts like eChart, Morris Chart etc.

It packed with all must have AJAX and CSS libraries for a Python Web Geek

The bootstrap is also a ready to use flask app, all you need to do is customize the custom script. The app uses blueprint to organize flask routes, which is automatically created based on based on modules.

You can develop database powered app with less pain in few hours with this awesome bootstrap from Colorlib.

Clone and start using the project today

git clone https://github.com/afourmy/flask-gentelella.git
cd flask-gentelella

For instruction and the bootstrap project please visit GitHub page

Have a look at my demo app hosted on heroku.com which is not using any database, it depends on simple json API