The Wayback Machine - https://web.archive.org/web/20240711190510/https://www.geeksforgeeks.org/how-to-create-a-simple-server-using-express-js/
Open In App

How to create a simple server using Express JS?

Last Updated : 01 Dec, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

In web application development, Express.js is one of the simplified frameworks for the creation of scalable web servers with proper features for building web and mobile applications. Express.js has list of middleware which makes developers easy to quickly set up servers, define routes, and handle HTTP requests.

Prerequisites

In this article, we will create a simple server using Express.js and also handle the client’s request for testing the created server using Express.js.

Steps to create a simple server using Express.js

Step 1: Firstly, we will make the folder named root by using the below command in the VScode Terminal. After creation use the cd command to navigate to the newly created folder.

mkdir root
cd root

Step 2: Once the folder is been created, we will initialize NPM using the below command, this will give us the package.json file.

npm init -y

2-min

Step 3: Once the project is been initialized, we need to install Express dependencies in our project by using the below installation command of NPM.

npm i express

Dependencies:

"dependencies": {
"express": "^4.18.2",
}

Step 4: Now create the below Project Structure in your project which includes public/index.html and server.js file.

4

Step 5: Now, we need to write code for our server.js file and in index.html.

server.js




// server.js
const express = require('express');
const app = express();
const port = 3000;
 
// Serving static files (HTML, CSS, JS)
app.use(express.static('public'));
// Defining a route for handling client communication
app.get('/api/message', (req, res) => {
    const message = 'Hello Geek. This Message is From Server';
    res.json({ message });
});
 
// Starting the server
app.listen(port, () => {
    console.log(`Server is listening at http://localhost:${port}`);
});


index.html




<!-- public/index.html -->
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Express.js Server</title>
</head>
<body>
    <h1>Client-Server Communication</h1>
    <button onclick="getMessage()">Get Message from Server</button>
    <p id="message"></p>
    <script>
        async function getMessage() {
            const response = await fetch('/api/message');
            const data = await response.json();
            document.getElementById('message').innerText = data.message;
        }
    </script>
</body>
</html>


To run the application, we need to start the server by using the below command.

node server.js

Output:

Output



Similar Reads

How to create a basic server using Express?
Express is a web application framework for NodeJS, simplifying the process of building robust and scalable web applications. It offers a simple design, making it easy to create APIs and handle HTTP requests and also support the middleware. Express is a popular choice for creating web servers and APIs in JavaScript. Steps to Create a basic Server Us
1 min read
How to create a simple web server that can read a given file on a given disk via “readFile” function ?
To create a web server we need to import the 'http' module using require() method and create a server using the createServer() method of the HTTP module. Syntax: const http = require('http') const server = createServer(callback).listen(port,hostname); Now in the callback in the createServer() method, we need to read the file from our local director
3 min read
How to create a simple HTTP server in Node ?
NodeJS provides a straightforward way to create HTTP servers, allowing developers to build web applications and APIs without relying on external web servers like Apache or Nginx. Let's explore how to create a simple HTTP server in NodeJS. Steps to Create a NodeJS Server:Step 1: Initialize the NPM using the below command. Using this the package.json
1 min read
How to Create a Simple Server in Node.js that Display Hello World ?
We will create a simple server in Node.js that returns Hello World using an express server. Node.js is a powerful JavaScript runtime built on Chrome's V8 engine, commonly used to build scalable network applications. One of the fundamental tasks when learning Node.js is creating a simple server that responds with "Hello World." This article will gui
2 min read
How to Create a Simple HTTP Server Listening at Port 3000 to Serve Video ?
Creating a simple HTTP server to serve a video file can be done using various programming languages and frameworks. For simplicity, we'll use Python, which has built-in modules that make this task straightforward. In this article, we’ll guide you through setting up a basic HTTP server using Python that listens on port 3000 and serves a video file.
3 min read
How to Create Multiple Routes in the Same Express.js Server ?
Creating multiple routes in an Express.js server involves defining routes in separate modules. This modular approach allows for better organization and maintainability by managing different routes independently and mounting them in the main server file. ApproachTo create multiple routes in an Express.js server, use express.Router() to define routes
2 min read
Create an Express server with EJS Templating Engine
EJS (Embedded JavaScript) is a simple and popular templating engine for JavaScript. it is designed to generate HTML markup with plain JavaScript. EJS is commonly used in server-side web applications built with Node.js. It allows you to generate dynamic HTML pages. In this article, we will create student data that includes fields like name, email, a
3 min read
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
2 min read
Build a Simple Web App with Express & Angular
A web application, or web app is a software application that runs on a web server and is accessed through a web browser over the internet. Web apps can be designed to perform a wide range of functions, such as allowing users to create and edit documents, manage their finances, purchase products, and access social networks. Web apps can be built usi
6 min read
Express.js express.text() Function
The express.text() function is a built-in middleware function in Express. It parses the incoming request payloads into a string and is based on body-parser. Syntax: express.text( [options] ) Parameter: The options parameter contains various properties like defaultCharset, inflate, limit, verify, etc. Return Value: It returns an Object. Installation
2 min read
three90RightbarBannerImg