Creating a web server using Express, a popular web application framework for Node.js, is a straightforward process. Here's a step-by-step guide:
Install Node.js and npm: Before you start, make sure you have Node.js and npm (Node Package Manager) installed on your computer. You can download Node.js, which comes with npm, from the official website: https://nodejs.org/
Create a new project directory: Open your terminal or command prompt and create a new directory for your project. You can do this with the mkdir
command followed by your directory name, for example: mkdir my-express-server
.
Navigate into your new directory: Use the cd
command to navigate into your new directory, for example: cd my-express-server
.
Initialize a new Node.js application: Run npm init -y
to create a new package.json
file with default settings.
Install Express: Run npm install express
to install Express.
Create a new file: Create a new file in your project directory named server.js
(or any name you prefer).
Write your server code: Open server.js
in a text editor and write the following code:
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 at http://localhost:${port}`);
});
This code creates a new Express application, sets up a route to respond to GET requests on the root URL ("/"), and starts the server listening on port 3000.
Start your server: Run node server.js
in your terminal.
Test your server: Open your web browser and navigate to http://localhost:3000. You should see the message "Hello World!".
That's it! You've created a basic web server using Express. From here, you can add more routes, handle different HTTP methods, serve static files, and more.