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

相关推荐
二川bro1 小时前
webpack 中 chunks详解
前端·webpack·node.js
Mintopia2 小时前
Node.js 学习的第三天,我们将深入学习 Express 框架
前端·javascript·node.js
WEI_Gaot2 小时前
npm 的解释和基本使用
npm·node.js
傻小胖2 小时前
在 Node.js 中设置响应的 MIME 类型
node.js
lh_12542 小时前
快速下载Node.js
node.js
晚风_END3 小时前
node.js|环境部署|源码编译高版本的node.js
linux·服务器·数据库·node.js·编辑器·个人开发
徐子童3 小时前
WebSocket介绍
网络·websocket·网络协议
风浅月明3 小时前
[Swift]Xcode模拟器无法请求http接口问题
http·xcode·swift
知道了啊11 小时前
websocket和SSE学习记录
websocket·网络协议·学习