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、调试服务等多种场景。

相关推荐
一叶飘零_sweeeet1 小时前
从字节到网页:HTTP 与 TCP 的底层密码全解析
tcp/ip·http·三次握手
我有一颗五叶草3 小时前
HTTP 协议
网络·网络协议·http
沐风ya3 小时前
RPC介绍
网络·网络协议·rpc
Yeats_Liao5 小时前
Go Web 编程快速入门 02 - 认识 net/http 与 Handler 接口
前端·http·golang
金梦人生5 小时前
🔥Knife4j vs Swagger:Node.js 开发者的API文档革命!
前端·node.js
前端赵哈哈5 小时前
那个让我熬夜三天的 “小数点”:一次 URL 踩坑记
前端·chrome·http
9527出列5 小时前
Netty源码分析--客户端连接接入流程解析
网络协议·netty
Ya-Jun6 小时前
快应用TypeError: The ‘compilation‘ argument must be an instance of Compilation错误
node.js·ux·js
L47546 小时前
SSL/TLS证书:保障网站安全的关键
网络协议·安全·ssl·tls
亮子AI7 小时前
【npm】npm install 产生软件包冲突怎么办?(详细步骤)
前端·npm·node.js