Hello world, if you are a newbie in Node.js, then you must be tempted for making your own server in your own local machine. So, if you are in this blog then you are at the right place. So let’s dive in.
You can also find this project in my GitHub repository-
A very simple API using node.js and express.js GitHub is home to over 50 million developers working together to host…
Step 1: First of all we’ll open the terminal and make one directory for our server application. Then we’ll navigate into that directory and run the command —
npm init. Then you will be asked to enter various details about your application, which will be stored as a json file named ‘Package.json’. Then you have to run another command to install the express module in that directory —
npm install express --save.
According to expressjs.com, Express is a fast, unopinionated, minimalist web framework for node.
Step 2: Now, we’ll create our server application file with the name of ‘app.js’ in the same directory. Then we’ll open this file in any text editor like Visual studio code,Notepad, Notepad++, Sublime Text 3 etc and write the following codes -
In the above code,
var express = require("express"); will import the express module into our application. Then,
var app = express(); will create an instance of express, named ‘app’. The third and the fourth line which contains
app.get() will respond to the GET request made by the browser. When the user will type
http://localhost:3000/in the browser, then the following code will be executed-
When the user will type
http://localhost:3000/one in the browser, then the following code will be executed-
Then, we need to make our server application listen to all the requests made by the browser, which will be achieved by the following command-
In this application, we have chosen port 3000, on which our server will listen to all the requests. You can choose any port of your choice.
Step 3: Now that we have written all the codes for our server application, we’ll save it and go back to terminal to run this using the command
node app.js. The following message will be displayed in the console -
Server listening on port: 3000
So, now our server is up and running.
Step 4: We’ll go the browser and enter the url
http://localhost:3000/ . The browser will display the following string —
Hi there, thanks for checking out my work. The server that is responding to you is developed using 'express.js' module in node.js. Please type 'localhost:3000/one' in your URL search bar to view the next page.
Now, we’ll enter another URL
http://localhost:3000/one . The browser will display the following string -
Have a nice day
In this article, we have discussed about the Express.js, we have created two API endpoints, which will accessed from the browser using GET request and finally we’ve made our server application to listen on port 3000.
A complete documentation for using express module.