How to create a simple web server with Node.js and Express.js

6 lug 2023 1 min di lettura
How to create a simple web server with Node.js and Express.js
Indice dei contenuti

Introduction

The tutorial will focus on building a basic web server using the JavaScript programming language, the Node.js runtime environment, and the Express.js framework.

Prerequisites

To follow this tutorial, you will need:

  1. A computer with a recent version of Windows, macOS, or Linux.
  2. Node.js and npm (Node Package Manager) installed on your computer. You can download Node.js and npm from the Node.js website.

Creating a new project

Create a new folder on your computer where you will host your project. Open a terminal or command prompt and navigate to that folder.

Once in the project folder, initialize a new Node.js project using npm. You can do this by running the following command in the terminal:

npm init -y

This command will create a new package.json file in your project folder.

Installing Express.js

Now that you have a Node.js project, you can install Express.js. To do this, run the following command in the terminal:

npm install express

This command will install Express.js and add it as a dependency in your package.json file.

Creating the web server

Create a new file called server.js in your project folder. Open this file in a text editor and enter the following JavaScript code:

//Import the express module
 const express = require('express');

 //Create a new express application
 const app = express();

 //Define a route for the root path (/)
 app.get('/', (req, res) => {
 res.send('Hello, World!');
 });

 //Start the server on port 3000
 app.listen(3000, () => {
 console.log('Server is running on http://localhost:3000');
 });

Starting the web server

You are now ready to start your web server. To do that, run the following command in the terminal:

node server.js

This command will start your web server on port 3000.

Open a web browser and visit http://localhost:3000. You should see your "Hello, World!" displayed on the page.

Conclusion

Congratulations! You have just created and successfully started your first web server using Node.js and Express.js. From here, you can start further exploring the capabilities of Node.js and Express.js to develop more complex web applications.

Support us with a

Successivamente, completa il checkout per l'accesso completo a Noviello.it.
Bentornato! Accesso eseguito correttamente.
Ti sei abbonato con successo a Noviello.it.
Successo! Il tuo account è completamente attivato, ora hai accesso a tutti i contenuti.
Operazione riuscita. Le tue informazioni di fatturazione sono state aggiornate.
La tua fatturazione non è stata aggiornata.