Open In App

Node.js Building simple REST API in express

Let’s have a brief introduction about the Express framework before starting the code section:
Express: It is an open-source NodeJs web application framework designed to develop websites, web applications, and APIs in a pretty easier way. 
Express helps us to handle different HTTP requests at specific routes.
As it is NodeJs web framework so make sure that NodeJs has been installed on our system.

For verifying type the following command in the terminal: 



node -v

It will show the installed version of NodeJs to our system as shown in the below screenshot.



npm init -y

For knowing more about package.json click here
 




// server.js File
const express = require('express'); // Importing express module
  
const app = express(); // Creating an express object
  
const port = 8000;  // Setting an port for this application
  
  
// Starting server using listen function
app.listen(port, function (err) {
   if(err){
       console.log("Error while starting server");
   }
   else{
       console.log("Server has been started at "+port);
   }
})

node server.js

app.get('/', function (req, res) {
  res.send('we are at the root route of our server');
})

Now, restart the server by typing the following command :

node server.js
Article Tags :