Express: Back-End Framework

Express is a Node.js framework. Rather than writing the code using Node.js and creating loads of Node modules, Express makes it simpler and easier to write the back-end code. Express helps in designing great web applications and APIs. Express supports many middlewares which makes the code shorter and easier to write.

Why use Express?

  • Asynchronous and Single-threaded.
  • Effecient, fast & scalable
  • Has the biggest community for Node.js
  • Express promotes code reusability with its built-in router.
  • Robust API

Follow the steps:

  • Create a new folder to start your express project and type below command in the command prompt to initialize a package.json file. Accept the default settings and continue.
npm init
  • Then install express by typing the below command and hit enter. Now finally create a file inside the directory named index.js.
npm install express --save
  • Now type in the following in index.js to create a sample server.
     
const express = require('express'), 
http = require('http'); 
  
const hostname = 'localhost'; 
const port = 8080; 
const app = express(); 
  
app.use((req, res) => { 
  console.log(req.headers); 
  res.statusCode = 200; 
  res.setHeader('Content-Type', 'text/html'); 
  res.end('<html><body><h1>This is a test server</h1></body></html>'); 
  
}); 
const sample_server = http.createServer(app); 
  
sample_server.listen(port, hostname, () => { 
  console.log(`Server running at http://${hostname}:${port}/`); 
});

 

  • Update the “scripts” section in package.json file

  • Then to start the server by running the below command
npm start
  • Now you can open the broswer and get the output of the running server.

 

Discussion

Be the first one to comment!