🎯 第 12 课:使用内置 http 模块创建 Web 服务器

2 阅读1分钟

太棒了!👏 你已经掌握了现代异步编程的核心技能,现在我们进入激动人心的环节:


📌 核心知识点
Node.js 内置的 http 模块可以让你用几行代码就启动一个 Web 服务器,响应浏览器请求。


🚀 第一个 Web 服务器

// server.js
const http = require('http');

// 创建服务器
const server = http.createServer((req, res) => {
  // req: 请求对象(Request)
  // res: 响应对象(Response)

  res.writeHead(200, { 'Content-Type': 'text/plain; charset=utf-8' });
  res.end('Hello, 我是你的第一个 Node.js 服务器!\n');
});

// 监听端口
const PORT = 3000;
server.listen(PORT, () => {
  console.log(`✅ 服务器已启动:http://localhost:${PORT}`);
});

✅ 运行它:

node server.js

输出:

✅ 服务器已启动:http://localhost:3000

👉 打开浏览器访问 http://localhost:3000

你会看到:

Hello, 我是你的第一个 Node.js 服务器!

🎉 恭喜!你已经成功搭建了一个真正的 Web 服务!


🔍 拆解每一部分

1. 引入模块

const http = require('http');

👉 使用 Node.js 内置的 HTTP 模块。


2. 创建服务器

http.createServer((req, res) => {
  // 每当有请求进来时,这个函数就会被调用
});
  • req:请求对象
    包含客户端信息:URL、方法、头等
    例如:req.url, req.method
  • res:响应对象
    用来向客户端发送数据
    常用方法:res.writeHead(), res.end()

3. 设置响应头和内容

res.writeHead(200, { 
  'Content-Type': 'text/plain; charset=utf-8' 
});
  • 200:HTTP 状态码,表示“成功”
  • 'text/plain':纯文本格式
  • 加上 charset=utf-8 支持中文显示

其他常见类型:

  • text/html → HTML 页面
  • application/json → JSON 数据

4. 发送响应并结束

res.end('你要返回的内容');

⚠️ 记住:必须调用 res.end(),否则浏览器会一直等待!


💡 扩展:根据 URL 返回不同内容

修改 server.js

const http = require('http');

const server = http.createServer((req, res) => {
  const { url, method } = req;

  if (url === '/' && method === 'GET') {
    res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' });
    res.end(`
      <h1>首页</h1>
      <p>欢迎来到我的 Node.js 服务器!</p>
      <a href="/about">关于我们</a>
    `);
  } 
  else if (url === '/about' && method === 'GET') {
    res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' });
    res.end('<h1>关于我们</h1><p>这是一个用 Node.js 构建的简单网站。</p>');
  } 
  else if (url === '/api/user' && method === 'GET') {
    res.writeHead(200, { 'Content-Type': 'application/json; charset=utf-8' });
    res.end(JSON.stringify({ id: 1, name: "Alice", age: 20 }));
  } 
  else {
    res.writeHead(404, { 'Content-Type': 'text/plain; charset=utf-8' });
    res.end('404 找不到页面');
  }
});

const PORT = 3000;
server.listen(PORT, () => {
  console.log(`✅ 服务器运行中:http://localhost:${PORT}`);
});

现在你可以访问:

地址效果
http://localhost:3000显示首页
http://localhost:3000/about关于我们页
http://localhost:3000/api/user返回 JSON 数据
其他路径404 提示

✅ 小结一句话:

使用 http.createServer() 可以监听请求,通过判断 req.urlreq.method 返回不同的内容,这是构建 Web 应用的起点。


📬 下一课预告:
第 13 课:深入理解 requestresponse —— 如何解析查询参数、处理 POST 数据?

我们将学习如何接收用户提交的表单或 JSON 数据。