Node.js 创建 HTTP 服务端

发布于:2025-04-21 ⋅ 阅读:(21) ⋅ 点赞:(0)

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


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

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


✅ 二、最基础用法

// 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. 区分路由

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)

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:

npm install express

基础使用:

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. 端口占用处理

监听报错:

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

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

res.setHeader('Access-Control-Allow-Origin', '*');

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

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):

ifconfig | grep inet

✅ 八、总结一句话版本

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


网站公告

今日签到

点亮在社区的每一天
去签到