Sign in
Log inSign up

Getting Started with ExpressJs

Nipun Verma's photo
Nipun Verma
·Dec 27, 2021·

4 min read

What is ExpressJs ? 🤔

ExpressJs is a Light Weight NodeJs based Web Application Framework written in JavaScript, used for designing and building web applications quickly and easily. It provides a fast and flexible development platform for creating applications.

Core Features:

  • It supports Routing
  • It supports MVC architectural pattern
  • It allows middlewares to respond to HTTP requests
  • It allows dynamically render HTML pages based on arguments passed to templates

Installing dependencies

We need to install express js, there are different ways to do it. The most common method is by using npm or yarn.

npm install express

or

yarn add express

Installing other dependencies

npm install nodemon axios

nodemon is a module that automatically develops a NodeJs based application when the changes are detected in the directory files. Additionally, make sure to change the scripts in the package.json file. Axios is a promise-based HTTP client for NodeJs. It makes it easy to send asynchronous HTTP requests to REST endpoints and perform CRUD operations.

"scripts" :{
     "devStart": "nodemon server.js"
}

server.js is the main file of the express sever.

Boot the server using the following command

npm run devStart

Create a file server.js

This file contains all the necessary stuff that is required for the web application.

// importing express and its creating instance
const express = require('express');
const app = express();
const PORT = 3030;

app.listen(PORT, ()=> {
     console.log(`Listening to port ${PORT}`);
});

This app variable can do all sorts of stuff, e.g., create routes, modify settings, connect to the port, and many more. app.listen() method binds the port with the connections on the specified host. It takes two arguments, the first argument is the port number on which the app listens, and the second argument is a callback function that gets executed every time the app gets connected to the port.

Basic Hello World code

GET Request

const express = require('express');
const app = express();
const PORT = 3030;

app.get('/', (req, res)=> {
     res.send('Hello World');
});

app.listen(PORT, ()=> {
     console.log(`Listening to port ${PORT}`);
});

So here, starting with the first route to '/', we first specified HTTP GET request, which is used by default to render web pages. Here in app.get() method, the first argument '/' is the route to our web page. The second argument is a callback function that gets executed each time the client requests this '/' route. This callback function takes two arguments, the first argument is req or request, which the client sends to the server, and the second argument is res or response, which the server sends back to the client. Here server sends res.send(), which contains a "Hello World" string. There is also a third parameter, ' next', a callback argument to the middleware function, called "next" by convention.

POST Request

const express = require('express');
const app = express();
const PORT = 3030;
app.use(express.json());
app.POST('/', (req, res)=> {
     // req.body;     JavaScript object containing the parse JSON
     res.json(req.body);
});

app.listen(PORT, ()=> console.log(`Listening to port ${PORT}`));

The app. use() method is used to mount the specified middleware function(s) at the path which is being specified. It is mostly used to set up middleware for your application.

Here we have specified express.json(), which is one of the in-built middleware of express. It parses any incoming request with JSON payloads and is based on body-parser.

const axios = require('axios');
const res = await axios({
     method: 'POST',
     url: 'localhost:3030/',
     headers: {
          'Content-Type' : 'Application/json'
     },
     data: {  answer: 30 }
});
const data = await res.json();
console.log(data);     // output -> {answer: 30}

API headers are like an additional source of information for each API call you make. 'Content-Type: 'Application/json' means that we send JSON data to the server and receive JSON data from the server. By declaring content type to application/json, the standard that the client and server understand. API data is now in the form of JSON sent to the server.

What are Middlewares ?

Middleware functions are functions that have access to the request object (req), the response object (res), and the next middleware function in the application’s request-response cycle.

So what exactly middlewares can do ?

  • Make changes to request and response object
  • Execute any code
  • End the request cycle
  • Invoke the next middleware

Example

// sample code
const express = require("express");
const app = express();
const PORT = 3030;

const middlewareFunction = (req, res, next)=> {
     console.log('Inside middleware function');
     // can also manipulate req object and return it in res object

     next();
}
app.use(middlewareFunction);

app.get('/', middlewareFunction, (req, res)=> {
     console.log('inside get request');
     res.send('middleware function example');
});

app.listen(PORT, ()=> console.log(`Listening to port ${PORT}`));

middlewareFunction is passed to app.use() method to register it as a middleware for our app before executing '/' end point logic. next() method is a function which, when invoked, executes the next middleware succeeding the current middleware.

Thank you for reading. Hope you found this post helpful !!