Node.js 创建 HTTP 服务端

Node.js 创建 HTTP 服务端的用法总结 ,内容涵盖了 核心模块、基本用法、Express 简化用法、常见场景、错误处理、以及实用小贴士。


✅ 一、Node.js 创建 HTTP 服务的方式

Node.js 使用内置的 http 模块即可快速创建一个 Web 服务,无需额外安装依赖。


✅ 二、最基础用法

js 复制代码
// server.js
const http = require('http');

const server = http.createServer((req, res) => {
  // 设置响应头
  res.writeHead(200, { 'Content-Type': 'text/plain' });

  // 发送响应内容
  res.end('Hello, Node.js HTTP Server!');
});

// 启动服务器
server.listen(3000, () => {
  console.log('HTTP server is running at http://localhost:3000');
});

✅ 三、常用功能场景

1. 区分路由

js 复制代码
const server = http.createServer((req, res) => {
  if (req.url === '/' && req.method === 'GET') {
    res.end('Home Page');
  } else if (req.url === '/about') {
    res.end('About Page');
  } else {
    res.statusCode = 404;
    res.end('Not Found');
  }
});

2. 处理 POST 请求数据(收集 body)

js 复制代码
const server = http.createServer((req, res) => {
  if (req.method === 'POST' && req.url === '/data') {
    let body = '';
    req.on('data', chunk => {
      body += chunk;
    });
    req.on('end', () => {
      console.log('Received:', body);
      res.end('Data received');
    });
  } else {
    res.end('Only POST to /data supported');
  }
});

✅ 四、使用 Express 简化开发(推荐)

安装 Express:

bash 复制代码
npm install express

基础使用:

js 复制代码
const express = require('express');
const app = express();

app.use(express.json()); // 支持 JSON 请求体

app.get('/', (req, res) => {
  res.send('Hello Express!');
});

app.post('/data', (req, res) => {
  console.log(req.body);
  res.send('Data received!');
});

app.listen(3000, () => {
  console.log('Express server running at http://localhost:3000');
});

✅ 五、错误处理 & 小技巧

1. 端口占用处理

监听报错:

js 复制代码
server.on('error', (err) => {
  if (err.code === 'EADDRINUSE') {
    console.error('端口已被占用');
  } else {
    console.error('服务器错误:', err);
  }
});

2. 设置跨域(CORS)响应头

js 复制代码
res.setHeader('Access-Control-Allow-Origin', '*');

3. 读取静态文件(搭配 fs)

js 复制代码
const fs = require('fs');
if (req.url === '/index.html') {
  fs.readFile('./index.html', (err, data) => {
    res.setHeader('Content-Type', 'text/html');
    res.end(data);
  });
}

✅ 六、典型应用场景

场景 示例
接收前端表单请求 POST /submit-form
提供前端页面 GET /index.html
API 服务接口 GET /api/list
提供静态资源 GET /images/logo.png
搭配 WebSocket 实现实时通信 配合 ws 模块使用

✅ 七、服务启动后访问方式

本地访问:

复制代码
http://localhost:3000

局域网访问(查看你的局域网 IP):

bash 复制代码
ifconfig | grep inet

✅ 八、总结一句话版本

使用 http.createServer() 快速创建原生服务,复杂逻辑推荐配合 express;Node HTTP 模块轻量强大,适合 API、Mock、调试服务等多种场景。

相关推荐
沫璃染墨1 小时前
从零入门计算机网络系列(十四):TCP报文与字节流本质——从数据封装到报文边界
linux·服务器·网络·网络协议·tcp/ip·tcp
byte轻骑兵3 小时前
【LMP】规范精讲[13]: 参数的户口本、公钥的集装箱与出厂的兜底值
人工智能·网络协议·人机交互·lmp·蓝牙链路管理
流浪0013 小时前
计算机网络篇17:传输层——TCP 超时重传、三次握手与四次挥手,TIME_WAIT 为什么要等 2MSL
网络协议·tcp/ip·计算机网络·三次握手·四次挥手·超时重传
AI 编程助手GPT19 小时前
curl 返回成功就能收文件?用本地 HTTP 验证错误页与超时
网络·网络协议·http
流浪00121 小时前
计算机网络篇16:传输层——TCP 报头属性字段:16 位窗口大小撑起流量控制,六个标志位标识报文类型
网络协议·tcp/ip·计算机网络·urg紧急指针·tcp报头
apollo_qwe21 小时前
接口超时了,前端为什么不能直接重试?
javascript·http
Jongkhurun1 天前
以太网的最小帧长为什么是 64 字节:从 CSMA/CD 冲突窗口推导 64 Byte
网络协议
honsor2 天前
SNMP 读取以太网温湿度传感器数据,监控平台对接实操
物联网·网络协议·tcp/ip
Yves..2 天前
HTTP 协议学习笔记:从报文结构到抓包实践
网络协议·http·fiddler
沫璃染墨2 天前
从零入门计算机网络系列(十二):HTTP长连接与会话管理详解——从Connection到Cookie与Session
linux·服务器·c++·tcp/ip·ubuntu·http·交互