user
How to create a web server with Express ?
alphonsio

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:

  1. 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/

  2. 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.

  3. Navigate into your new directory: Use the cd command to navigate into your new directory, for example: cd my-express-server.

  4. Initialize a new Node.js application: Run npm init -y to create a new package.json file with default settings.

  5. Install Express: Run npm install express to install Express.

  6. Create a new file: Create a new file in your project directory named server.js (or any name you prefer).

  7. 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.

  1. Start your server: Run node server.js in your terminal.

  2. 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.