Tutorial
create Server with Express JS

Create Server with Express JS

Basic Setup

▶️ Basic Setup

  1. Create a folder for your project and open it in your code editor using the following command:
code .
  1. Now open the terminal and hit npm init -y to create a package.json file for our project
  2. We need to install express so hit npm i express in the terminal
  3. Create a app.js file in the root directory using echo > app.js command
  4. Install nodemon as a dev dependency using npm i nodemon command

▶️ Connect to Server

  1. Open your package.json file and change the start script to
package.json
 
 "scripts": {
    "start": "node app.js",
    "dev": "nodemon app.js"
  },
  1. Open your app.js file and add the following code
app.js
 
const express = require("express"); // Importing the express module
const app = express(); // Creating an express app
 
// Port
const PORT = process.env.PORT || 5000; // Setting the port number
 
// Home Page
app.get("/", (req, res) => { // Creating the home page route
  res.send("Subham's Home Page");
});
 
// Async Function
const start = async () => { // Creating an async function to start the server
  try {
    app.listen(PORT, () => { // Starting the server and listening for incoming requests on the specified port number
      console.log(`Server is running on port ${PORT}`); // Logging a message to the console once the server has started and is listening for incoming requests
    });
  } catch (error) { // Handling errors that occur during server startup
    console.log(error);
  }
};
 
// Call the start function to start the server
start(); // Calling the async function to start the server

▶️ Explanation of the Code

⚡ Importing Express Module

The first line const express = require("express"); imports the "express" module which is a node.js web application framework that allows us to build web applications easily. We use the require() function to import the module and assign it to a constant variable called express.

⚡ Creating an Express App

Next, we create an instance of the express module by calling the express() function and store it in a constant variable called app. This app variable is used to interact with the express module and build our web application.

⚡ Port

  • In the line const PORT = process.env.PORT || 5000;, we set the port number for our web application.
  • process.env.PORT refers to the environment variable called "PORT".
  • If this environment variable is set, we use its value as the port number. Otherwise, we default to port number 5000.

⚡ Home Page

  • The line app.get("/", (req, res) => { ... }); creates a route for our web application's home page.
  • The .get() method specifies that this route should handle HTTP GET requests to the root URL ("/") of our web application.
  • The callback function (req, res) => { ... } is called when a GET request is received.
  • req and res are objects representing the request and response, respectively.
  • The res.send() function sends a response back to the client with the text "Subham's Home Page".

⚡ Async Function

  • The line const start = async () => { ... } defines an async function called start.
  • This function starts our web server and listens for incoming requests on the specified port number.
  • Inside the function, we have a try-catch block to handle any errors that may occur during server startup.

Starting the Server

  • The line app.listen(PORT, () => { ... }); starts the server and listens for incoming requests on the specified port number.
  • The first argument to app.listen() is the port number to listen on, which we set using the PORT constant variable.
  • The second argument is a callback function that logs a message to the console once the server has started and is listening for incoming requests.

Error Handling

  • If any error occurs during the process of starting the server, the catch block will catch the error and log it to the console using console.log(error).

⚡ Calling the Async Function to Start the Server

  • The last line of code start(); calls the start function we defined earlier to start the server.
  • This is the final step in starting our web application.