ExpressJs

Posted on December 8, 2021 at 09:41 AM

Express-JS

Express is a minimal and flexible Node.js web application framework that provides a robust set of features for web and mobile applications.

To Create Mobile Application, Single page applications or for AJAX calls to get data to render at client end, APIs play a crucial role to fetch from server side with the HTTP utility methods and middleware, creating a robust API is quick and easy in Express JS.

Express provides a thin layer of fundamental web application features, without obscuring Node.js features that you know and love.

Installation & Setup

To install express js framework we need to setup a new node project with 

npm init

Once the project is initialized now we can start installing the express js in the project directory

npm install express –save

As the installation is done you will notice that express with its version is added in dependencies of package.json file.

Installation & Setup

Now we will set up the entry gate of our project with setting up app.js or index.js whatever you choose at the time of npm init.

index.js

In the above screen shot you can have a look that we have setup the entry gate of the app.

So i am explaining this line by line as in 

Line 1: we have required the express package in variable.

Line 2: Then we are storing the express core function in the app variable through which we can use the methods of express throughout the file.

Line 3: We need a port to run this application so storing the port 3000 in variable to use in future.

Line 4: We are setting up the first base route and it has a callback function with req and res parameters that help to communicate as to get data and headers in req and same to send the response in res and it is used in line 7.

Line 10: To run this project a port is required to listen to the request and or send the response. So assign the port.

Ok so that was the explanation about the app.js file and to run the application we need to execute some command in terminal here it is 

node app.js

node app.js

In the above screen shot we can see the two consoles that were mentioned in code at line 11 & line 6.

Base Routing

Routing means a path where the user can communicate to get or send data that can be accessed through routing methods such as GET, POST, PUT, DELETE, etc.

Structure of create a route in expressJs

app.Method(PATH, HANDLER Function);  

Eg

GET Request 

The HTTP GET method requests a representation of the specified resource.

GET Request

Response 

Response

POST Request

The HTTP POST method sends data to the server.

HTTP POST method

In this we have added a middleware body-parser to receive data from the client end and that can be accessed in req.body. So if you are not aware about middleware it is cover in next section.

Response:

middleware it is cover in next section

Middleware

Middleware function are used to add between the path and handler in express route are in express application 

app.use((req,res,next)=>{ next() });

In above example of post api urlencodeparser is middleware which help to get post data in req.body

Middleware

More example for understanding

More example for understanding

As in the first image we have created a logger function which is used as a middleware in get request as whenever client requests the get api it will log in console as shown in 2nd image.

Middleware is mostly used for token Validation or changes in req header before the handler function executes.

Static Routing 

To access static files in project expressjs have built-in middleware express.static() where we can provide the directory to make static that can be accessed by requesting the file structure.

Static Routing 

 

Here is the example in above screen shot were we have index.html in public folder which we make a static folder so it can be accessed by http://localhost:3000/static/

View Engine Setup 

Template engines convert the template file and data into an html file and send that file to the client side to render.

Need to install the template engine npm i pug in terminal

Setting up the engine

View Engine Setup 

In the above image we have set the view engine of the pug. And in route we have render the pug file by mentioning the file name in the views directory with title variable value and message value.

variable value

We need to create a file with extension of pug as we are using pug template engine to render views so it should be in views directory in the root folder. for more details to write pug files visit https://www.npmjs.com/package/pug

root folder

Mysql Database Connection

=> For Database connection you need a mysql database installed in your system or you need your connection details if you are connecting remotely.

Need to add the code in app.js 

  1. As in start we need to install the mysql package as npm i mysql.
  2. Initially we need to require the package and store it in const mysql.
  3. After that we need to create a mysql connection as we get the createconnection method in the mysql package to create a connection and pass the required parameters to create a connection.
  4. And now we have to connect the connection as we need to use the connect method and we get a callback to handle the connection.
  5. Once connection is established without any error we can use the query method to pass the mysql query to SELECT, UPDATE , DELETE  query to manipulate data in Database.
  6. To demonstrate the connection we have fetched data from the database and rendered the response in /get-db-data route.
  7. Save the code and then run the project with node app.js  and then hit the route /get-db-data

Mysql Database Connection

mysql

MongoDB Database Connection

For mongodb database connection you need to install mongodb in your system and should have basic knowledge of mongo db collections.

  1. Firstly need to install mongodb package npm install mongodb 
  2. At initial need to require the package in code and store in variable.
  3. After that we need to connect mongodb by giving a path for that we need to use the connect method of mongodb which we can get from the MongoClient variable as we have required the mongodb package.
  4. In the callback function we will get the error and client as we get error it will throw error if not then we can use client to connect to db client.db(‘db_name’) and store this in a variable which can be used further.
  5. In the route we can connect to the collection to get the data by providing the collection name in db.collection(‘collection_name’) and with find() will find the collection and then convert into an array with toArray() which will have a callback.
  6. In callback function we will get err and result as if we got err it will throw the err else we can render the received data from that provided collection.

provided collection.

Response:

Response:

Advantages of ExpressJS 

  • Javascript language is used in ExpressJS framework
  • Scale application quickly
  • Community Support
  • Supported by Google v8 engine
  • Low maintenance cost

Disadvantages of ExpressJS 

  • Event Driven Programming( Callbacks )
  • Middleware

Source Code URL : https://github.com/nilemandal22/express-js-base-template 

Thank You.

Related Posts

Start a Project

We could talk tech all day. But we’d like to do things too,
like everything we’ve been promising out here.