Building an Express.js Web App: Part 2 – Setting up an Express.js Server 💻

Posted by

Express.js Web App

Creating an express.js server 💻

In part 1 of our Express.js web app series, we covered the basics of setting up an Express.js application and creating a simple web page. In this article, we will focus on creating an Express.js server to handle client requests and serve dynamic content.

First, let’s start by creating a new file called server.js in our project directory. This file will serve as the entry point for our Express.js server. We can use the following code as a starting point:

        
const express = require('express');
const app = express();
const port = 3000;

app.get('/', (req, res) => {
    res.send('Hello, World!');
});

app.listen(port, () => {
    console.log(`Server is running on http://localhost:${port}`);
});
        
    

In the code above, we first require the express module and create an instance of the express application. We then define a route for the root URL using the app.get() method, which takes a path and a callback function as arguments. The callback function is called when a GET request is made to the specified path, and it takes a request and response object as arguments. Inside the callback function, we use the res.send() method to send a simple “Hello, World!” message back to the client.

Finally, we call the app.listen() method to start the server on port 3000, and we log a message to the console to indicate that the server is running.

To start the server, we can run the following command in the terminal:

        
node server.js
        
    

Now, if we open a web browser and navigate to http://localhost:3000, we should see the “Hello, World!” message displayed on the page.

Congratulations! You have successfully created an Express.js server to handle client requests and serve dynamic content. In the next part of our series, we will cover how to work with routes and middleware in Express.js. Stay tuned!

0 0 votes
Article Rating
4 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Aladdinme
7 months ago

Hi, great tutorial! just moula7dha s8ira 7abit n9oulha fi 3oudh metekteb fel URL "localhost:3000" sob extension fi vscode esmha "liveserver" besh tkoun el 5edma ashel w 5ir.

Molka Molka
7 months ago

bravo kmllll yatiikk saha

Aloui Ilyes
7 months ago

Wasel khouya rabii maak ❤️

jusstAli
7 months ago