Node.js 服务搭建:从零到部署的生产级指南

1. 基本 HTTP 服务器

1.1 使用内置的 http 模块

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

const server = http.createServer((req, res) => {
  // 设置响应头
  res.writeHead(200, { 'Content-Type': 'text/plain' });
  
  // 根据 URL 路由
  if (req.url === '/') {
    res.end('首页');
  } else if (req.url === '/about') {
    res.end('关于我们');
  } else {
    res.end('页面未找到');
  }
});

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

2. 使用 Express 框架(推荐)

2.1 安装 Express

bash 复制代码
npm init -y
npm install express

2.2 基本 Express 服务器

javascript 复制代码
// app.js
const express = require('express');
const app = express();
const PORT = 3000;

// 中间件:解析 JSON 请求体
app.use(express.json());

// 静态文件服务
app.use(express.static('public'));

// 路由
app.get('/', (req, res) => {
  res.send('首页');
});

app.get('/api/users', (req, res) => {
  res.json([
    { id: 1, name: '张三' },
    { id: 2, name: '李四' }
  ]);
});

app.post('/api/users', (req, res) => {
  const user = req.body;
  // 保存用户逻辑
  res.status(201).json({ message: '用户创建成功', user });
});

// 错误处理中间件
app.use((err, req, res, next) => {
  console.error(err.stack);
  res.status(500).send('服务器错误');
});

// 404 处理
app.use((req, res) => {
  res.status(404).send('页面未找到');
});

app.listen(PORT, () => {
  console.log(`服务器运行在 http://localhost:${PORT}`);
});

3. 项目结构示例

复制代码
my-server/
├── package.json
├── app.js              # 主入口文件
├── .env               # 环境变量
├── public/            # 静态文件
│   ├── css/
│   ├── js/
│   └── images/
├── routes/            # 路由文件
│   ├── userRoutes.js
│   └── productRoutes.js
├── controllers/       # 控制器
├── models/           # 数据模型
├── middleware/       # 自定义中间件
└── config/          # 配置文件

3.1 模块化路由

javascript 复制代码
// routes/userRoutes.js
const express = require('express');
const router = express.Router();

router.get('/', (req, res) => {
  res.json([{ id: 1, name: '用户1' }]);
});

router.get('/:id', (req, res) => {
  res.json({ id: req.params.id, name: '用户' + req.params.id });
});

module.exports = router;
javascript 复制代码
// app.js 中使用路由
const userRoutes = require('./routes/userRoutes');

app.use('/api/users', userRoutes);

4. 常用中间件安装

bash 复制代码
# 常用依赖包
npm install express         # Web框架
npm install cors           # 跨域支持
npm install helmet         # 安全头部
npm install morgan         # 请求日志
npm install dotenv         # 环境变量
npm install compression    # 响应压缩

# 数据库相关
npm install mongoose       # MongoDB
npm install mysql2         # MySQL
npm install sequelize      # ORM

# 验证相关
npm install bcrypt         # 密码加密
npm install jsonwebtoken   # JWT认证
npm install express-validator # 数据验证

5. 完整的生产环境配置

javascript 复制代码
// app.js
const express = require('express');
const cors = require('cors');
const helmet = require('helmet');
const morgan = require('morgan');
const compression = require('compression');
require('dotenv').config();

const app = express();

// 中间件配置
app.use(helmet()); // 安全头部
app.use(cors()); // 跨域支持
app.use(compression()); // 响应压缩
app.use(morgan('combined')); // 日志
app.use(express.json()); // 解析 JSON
app.use(express.urlencoded({ extended: true })); // 解析表单数据

// 路由
app.get('/health', (req, res) => {
  res.json({ status: 'OK', timestamp: new Date() });
});

// API 路由
app.use('/api', require('./routes/api'));

// 错误处理
app.use((err, req, res, next) => {
  console.error(err);
  res.status(err.status || 500).json({
    error: {
      message: err.message || '服务器内部错误',
      ...(process.env.NODE_ENV === 'development' && { stack: err.stack })
    }
  });
});

// 启动服务器
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
  console.log(`🚀 服务器启动成功`);
  console.log(`📡 地址: http://localhost:${PORT}`);
  console.log(`🌍 环境: ${process.env.NODE_ENV || 'development'}`);
});

6. 使用 PM2 进程管理

bash 复制代码
# 全局安装 PM2
npm install -g pm2

# 启动应用
pm2 start app.js --name "my-server"

# 常用命令
pm2 list              # 查看进程列表
pm2 logs my-server    # 查看日志
pm2 restart my-server # 重启
pm2 stop my-server    # 停止
pm2 delete my-server  # 删除

# 开机自启
pm2 startup
pm2 save

7. Docker 部署

dockerfile 复制代码
# Dockerfile
FROM node:18-alpine

WORKDIR /app

COPY package*.json ./
RUN npm ci --only=production

COPY . .

EXPOSE 3000

CMD ["node", "app.js"]

8. 快速启动脚本

json 复制代码
// package.json 中添加
{
  "scripts": {
    "start": "node app.js",
    "dev": "nodemon app.js",
    "test": "jest",
    "lint": "eslint .",
    "docker:build": "docker build -t my-server .",
    "docker:run": "docker run -p 3000:3000 my-server"
  }
}

9. 最佳实践建议

  1. 使用环境变量:敏感信息不要硬编码
  2. 错误处理:使用统一的错误处理中间件
  3. 日志记录:记录重要操作和错误
  4. 输入验证:验证所有用户输入
  5. 限流:防止 API 被滥用
  6. HTTPS:生产环境使用 HTTPS
  7. CORS:正确配置跨域策略
  8. 数据库连接池:优化数据库连接

快速开始

bash 复制代码
# 创建项目
mkdir my-server && cd my-server
npm init -y
npm install express cors helmet morgan dotenv

# 创建 app.js 文件
# 复制上面的 Express 示例代码

# 启动开发服务器
npm install -g nodemon
nodemon app.js

这样就完成了一个基本的 Node.js 服务器的搭建。根据你的具体需求,可以在此基础上添加更多功能模块。

相关推荐
毕设源码-朱学姐1 天前
【开题答辩全过程】以 基于Node.js的书籍分享平台设计与实现为例,包含答辩的问题和答案
node.js
前端 贾公子2 天前
Node.js 如何处理 ES6 模块
前端·node.js·es6
周杰伦的稻香2 天前
Hexo搭建教程
java·node.js
毕设源码-钟学长2 天前
【开题答辩全过程】以 基于node.js vue的点餐系统的设计与实现为例,包含答辩的问题和答案
前端·vue.js·node.js
朝朝暮暮an2 天前
Day 2|Node.js 运行机制、模块系统与异步初探
node.js
aidou13142 天前
Visual Studio Code(VS Code)安装步骤
vscode·npm·node.js·环境变量
止观止2 天前
告别 require!TypeScript 5.9 与 Node.js 20+ 的 ESM 互操作指南
javascript·typescript·node.js
一只专注api接口开发的技术猿2 天前
淘宝商品详情API的流量控制与熔断机制:保障系统稳定性的后端设计
大数据·数据结构·数据库·架构·node.js
天远数科3 天前
天远车辆过户查询API集成指南:Node.js 全栈视角下的二手车数据挖掘
大数据·数据挖掘·node.js·vim
全栈小53 天前
【前端】win11操作系统安装完最新版本的NodeJs运行npm install报错,提示在此系统上禁止运行脚本
前端·npm·node.js