Node.js 作为一种基于 Chrome V8 引擎的 JavaScript 运行时环境,凭借其异步非阻塞 I/O 模型和高性能的特点,已成为搭建 Web 服务器的热门选择,本文将详细介绍如何使用 Node.js 搭建 Web 服务器,包括基础实现、模块化扩展、性能优化及常见问题解决方案。

Node.js 搭建 Web 服务器的基础实现
Node.js 搭建 Web 服务器的核心是利用其内置的 http 模块。http 模块提供了创建 HTTP 服务器和客户端的方法,是 Node.js 进行网络通信的基础,以下是一个最简单的 Web 服务器实现示例:
// 引入 http 模块
const http = require('http');
// 创建服务器
const server = http.createServer((req, res) => {
// 设置响应头
res.writeHead(200, { 'Content-Type': 'text/plain; charset=utf-8' });
// 发送响应内容
res.end('Hello, Node.js Web Server!');
});
// 启动服务器,监听 3000 端口
server.listen(3000, () => {
console.log('Server is running at http://localhost:3000/');
});
代码解析:
require('http'):引入 Node.js 内置的http模块。http.createServer():创建一个 HTTP 服务器,接收一个回调函数作为参数,该函数在每次请求到达时执行。req(request 对象):包含请求信息,如请求方法、请求头、请求 URL 等。res(response 对象):用于向客户端发送响应,如设置响应头、发送响应数据等。
res.writeHead():设置响应状态码和响应头。200表示请求成功,'Content-Type'指定响应内容的类型和字符编码。res.end():结束响应并发送内容,调用该方法后,服务器将不再向客户端发送数据。server.listen():启动服务器并监听指定端口(本例为 3000),回调函数在服务器启动成功后执行。
运行上述代码后,在浏览器中访问 http://localhost:3000/,即可看到 "Hello, Node.js Web Server!" 的输出。
路由处理与动态响应
实际应用中,服务器需要根据不同的 URL 和请求方法返回不同的内容,此时需要实现路由功能,以下是一个简单的路由处理示例:

const http = require('http');
const server = http.createServer((req, res) => {
// 获取请求方法和 URL
const { method, url } = req;
// 设置响应头
res.setHeader('Content-Type', 'text/plain; charset=utf-8');
// 根据路由返回不同内容
if (method === 'GET' && url === '/') {
res.end('Welcome to the Homepage!');
} else if (method === 'GET' && url === '/about') {
res.end('About Us Page');
} else if (method === 'POST' && url === '/submit') {
let body = '';
req.on('data', chunk => {
body += chunk.toString();
});
req.on('end', () => {
res.end(`Received data: ${body}`);
});
} else {
res.writeHead(404);
res.end('404 Not Found');
}
});
server.listen(3000, () => {
console.log('Server is running at http://localhost:3000/');
});
代码改进:
- 通过
req.method和req.url获取请求方法和 URL,实现简单的路由判断。 - 对于 POST 请求,需要监听
req的data事件来获取请求体数据,并在end事件中处理并发送响应。
使用 Express 框架简化开发
虽然原生 http 模块可以搭建 Web 服务器,但在实际项目中,使用 Express 框架可以更高效地处理路由、中间件、模板引擎等功能,以下是使用 Express 搭建 Web 服务器的步骤:
安装 Express
在项目目录下运行以下命令安装 Express:
npm init -y npm install express
创建 Express 服务器
const express = require('express');
const app = express();
const port = 3000;
// 定义路由
app.get('/', (req, res) => {
res.send('Welcome to Express Server!');
});
app.get('/users/:id', (req, res) => {
const userId = req.params.id;
res.send(`User ID: ${userId}`);
});
// 启动服务器
app.listen(port, () => {
console.log(`Express server is running at http://localhost:${port}/`);
});
代码解析:

express():创建 Express 应用程序实例。app.get():定义 GET 请求的路由,第一个参数为 URL 路径,第二个参数为处理函数。req.params:获取路由参数(如id)。res.send():发送响应内容,Express 会自动设置响应头。
中间件的使用
中间件是函数,可以访问请求对象(req)、响应对象(res)和应用程序的请求-响应周期中的 next 函数,以下是一个中间件示例:
// 日志中间件
app.use((req, res, next) => {
console.log(`${req.method} ${req.url} - ${new Date().toISOString()}`);
next(); // 将控制权传递给下一个中间件或路由
});
// 解析 JSON 请求体的中间件
app.use(express.json());
// 解析 URL 编码请求体的中间件
app.use(express.urlencoded({ extended: true }));
静态文件服务与模板引擎
静态文件服务
Express 提供了内置的中间件 express.static 来服务静态文件(如 CSS、JavaScript、图片等):
app.use(express.static('public')); // public 目录下的文件可通过 URL 直接访问
假设 public 目录下有一个 style.css 文件,则可通过 http://localhost:3000/style.css 访问。
模板引擎
模板引擎用于动态生成 HTML 页面,Express 支持 EJS、Pug、Handlebars 等模板引擎,以下是使用 EJS 的示例:
安装 EJS
npm install ejs
配置 EJS 并渲染模板
app.set('view engine', 'ejs'); // 设置模板引擎
app.set('views', './views'); // 设置模板文件目录
app.get('/profile', (req, res) => {
const user = { name: 'Alice', age: 25 };
res.render('profile', { user }); // 渲染 profile.ejs 文件
});
views/profile.ejs 文件内容:
<!DOCTYPE html> <html> <head>User Profile</title> </head> <body> <h1>User: <%= user.name %></h1> <p>Age: <%= user.age %></p> </body> </html>
性能优化与部署
性能优化
-
集群模式:利用 Node.js 的
cluster模块实现多进程,充分利用多核 CPU:const cluster = require('cluster'); const os = require('os'); if (cluster.isMaster) { const cpuCount = os.cpus().length; for (let i = 0; i < cpuCount; i++) { cluster.fork(); // 创建工作进程 } } else { // 工作进程中启动服务器 app.listen(3000); } -
缓存:使用 Redis 等工具缓存常用数据,减少数据库查询。
-
压缩响应:使用
compression中间件压缩响应数据:npm install compression
const compression = require('compression'); app.use(compression());
部署
- 使用 PM2:PM2 是一个流行的 Node.js 进程管理器,支持集群模式、日志管理等功能。
安装 PM2:
npm install pm2 -g
启动应用:
pm2 start app.js -i max # -i max 表示自动使用所有 CPU 核心启动集群
- 反向代理:使用 Nginx 作为反向代理,处理静态文件、负载均衡和 HTTPS。
相关问答 FAQs
问题 1:Node.js 搭建 Web 服务器时,如何处理跨域(CORS)问题?
解答:跨域资源共享(CORS)是浏览器出于安全考虑对跨域请求的限制,在 Express 中,可以使用 cors 中间件解决:
- 安装
cors:npm install cors
- 在应用中使用:
const cors = require('cors'); app.use(cors()); // 允许所有来源的跨域请求 // 或配置特定来源 // app.use(cors({ origin: 'https://example.com' }));cors中间件会自动设置Access-Control-Allow-Origin等响应头,使浏览器允许跨域请求。
问题 2:Node.js Web 服务器如何处理文件上传?
解答:可以使用 multer 中间件处理文件上传,以下是示例:
-
安装
multer:npm install multer
-
配置文件上传路由:
const multer = require('multer'); const upload = multer({ dest: 'uploads/' }); // 上传文件存储在 uploads 目录 app.post('/upload', upload.single('file'), (req, res) => { if (!req.file) { return res.status(400).send('No file uploaded.'); } res.send(`File uploaded: ${req.file.originalname}`); });在前端表单中,需设置
enctype="multipart/form-data"和name="file"(与upload.single('file')中的参数一致)。req.file包含上传文件的信息,如文件名、大小、存储路径等。
