📜  ExpressJS-Hello World(1)

📅  最后修改于: 2023-12-03 14:41:05.234000             🧑  作者: Mango

ExpressJS-Hello World

Introduction

ExpressJS is a popular web application framework for Node.js. It provides a simple and minimalist approach to building web applications. In this tutorial, we will create a simple "Hello World" application using ExpressJS.

Prerequisites

Before starting this tutorial, you should have the following installed on your machine:

  • Node.js
  • npm
Step 1: Create a new project

Create a new directory for your project and navigate to it in the terminal.

$ mkdir my-express-app
$ cd my-express-app

Then, initialize a new Node.js project using npm.

$ npm init

Follow the prompts to customize your project (you can leave most of the options as default).

Step 2: Install ExpressJS

Next, install ExpressJS as a dependency for your project.

$ npm install express
Step 3: Create the "Hello World" application

Create a new file called index.js in your project directory.

$ touch index.js

Open the index.js file in your favorite code editor and add the following code:

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

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

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

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

This code creates a new Express application, defines a route handler for the root path (/), and starts the server on port 3000.

Step 4: Run the application

To run the application, execute the following command in your project directory:

$ node index.js

Open your web browser and go to http://localhost:3000. You should see the message "Hello World!" displayed in the browser.

Conclusion

Congratulations! You have successfully created your first ExpressJS application. ExpressJS is a powerful framework that allows you to build complex web applications with ease. You can now start exploring more of its features and building more advanced applications.