Create a basic web Server using express


A Framework gives a proper structure to our applications. And it makes our application code maintainable and understandable. There are various frameworks for building applications and web Servers. And Express is one of the most popular Frameworks for building applications.it is a fast, lightweight and well documented framework. And those characteristics became a obvious cause for its popularity.

Creating a basic web Server using express

Download express
Before install express Node.js should be installed.
Create a folder and open a terminal inside in that folder. 
to create the package JASON file first run npm init --yes command.















To install express.js run npm i express command














Let’s start coding
Open your favorite IDE and select the newly created folder as the workspace.
Next create a javaScript filecalled app.js.

  • In the first line express module has loaded using require method which returns another function.
  • In the second line object of that returned function have assigned to a variable call app.this app object consists of many useful methods which are correspondent to HTTP verbs.those are,
    • app.get()-implement endpoints that response HTTP GET request
    • app.post ()-handles HTTP post request
    • app.put()
    • app.delete()
  • Here we are going to use get method. In the 1st argument is the path (/-root of the website).2nd argument is the call back function which will be called when we have an HTTP GET request in this endpoint. This callback function have2 arguments called request and response Req-gives information about incoming request.when we get HTTP request to the root of our website should respond with a hello world message.
  • Finally we have to listen on a given port. For that listen method is used. It has 2 arguments 1st argument is the port number we are listening to, and 2nd argument is optional here it is used to print output on console.
  • Now save the file and open a terminal in the folder where we saved the javaScript file.
  • Run the following command in the terminal to execute javaScript file (app.js)









  • Once it’s done go to a browser and navigate to localhost:8080 and localhost:8080/page2





Comments

Popular posts from this blog

Consuming API from web application using OAuth 2.0

Simple REST API using Node,Express and MongoDB