推荐答案
// www.javascriptcn.com code example
// 1. 安装 Express
// 在终端中运行以下命令来安装 Express:
// npm install express
// 2. 创建 Express 应用
const express = require('express');
const app = express();
// 3. 定义路由
app.get('/', (req, res) => {
res.send('Hello, World!');
});
// 4. 启动服务器
const PORT = 3000;
app.listen(PORT, () => {
console.log(`Server is running on http://localhost:${PORT}`);
});本题详细解读
1. 安装 Express
在创建 Express 应用之前,首先需要安装 Express 模块。可以通过 npm(Node.js 的包管理工具)来安装 Express。在终端中运行以下命令:
npm install express
2. 创建 Express 应用
安装完成后,可以在项目中引入 Express 模块并创建一个 Express 应用实例。express() 函数会返回一个 Express 应用对象,通常将其赋值给一个变量(如 app)。
const express = require('express');
const app = express();3. 定义路由
Express 应用的核心功能之一是处理 HTTP 请求。可以通过定义路由来处理不同的请求。例如,以下代码定义了一个处理根路径 (/) 的 GET 请求的路由:
app.get('/', (req, res) => {
res.send('Hello, World!');
});在这个例子中,当用户访问根路径时,服务器会返回 "Hello, World!"。
4. 启动服务器
最后,需要启动服务器以监听来自客户端的请求。可以通过调用 app.listen() 方法来启动服务器,并指定监听的端口号。例如:
const PORT = 3000;
app.listen(PORT, () => {
console.log(`Server is running on http://localhost:${PORT}`);
});在这个例子中,服务器会监听 3000 端口,并在启动时打印一条消息到控制台。