Getting started with creating basic servers using Node.js and Express
In the following article, we will take a look at how to create a basic back-end server using Node.js and Server.
What is a Server?
Simply put a server is software/hardware at the back end that provides the front-end user/client with a response when for an incoming request by the user. It uses HTTP protocol to serve the front-end users.
What is Node.js?
Simply put Node.js is a runtime environment that developer uses to create back-end servers/APIs that run JavaScript code out of a browser.
To know more about NodeJS refer to this link:
What is Express?
Express.js or simply Express is a back-end web application framework that is used for building RESTful APIs using JavaScript. It is written in JavaScript and hosted on the Node.js runtime environment. It is highly flexible and has many modules that make it extremely popular for creating websites and REST APIs. Command to install Express:
npm i express
//Following command is used for requiring express in the //application
const express=require("express");
In this article, we will be creating a basic server that performs addition(+) operations on numbers.
What is a route in the back end?
The route is a URL that is mapped to some specific function or a piece of code. When the front-end user requests a specific route in the URL, the server will look it up in the back end and then execute the associated piece of code to that particular route. Below are some common routes that we see in web apps:
"/" -Home page of a website
"/login"-The login page of the website
"/checkout"- Takes to the ch3eckout page of the website
In our server, we will be using the "/add" route to take us to the required route.
Getting started with the coding part
Before starting to write the code we create the required files as shown below:
I am using Hyper terminal for navigating across files, creating files, installing the modules of Express etc.
Before installing Express we need to initialize the project using npm init
using the following system command in the project directory:
After some time some commands/questions will appear to which one has to answer yes(y) or no(n). All of those questions can be answered yes(y) by simply pressing the "Enter" key. After that, you should see something like this on the screen:
npm init will create a package.json in the project directory that will be used to store the various details of the project like name, version, dependencies etc.
Now we will see how to install and require Express in our project.
To install Express:-
npm i express