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 服务器的搭建。根据你的具体需求,可以在此基础上添加更多功能模块。

相关推荐
天远云服2 小时前
Node.js实战:天远车辆出险查询API接口调用流程、代码接入与场景应用
大数据·node.js
摇滚侠2 小时前
安装完 node.js 以后,需不需要修改全局安装包的目录,我觉的不需要修改。网上有很多教程让修改全局包安装目录和配置环境变量,我觉的这两步都多余。
node.js
muddjsv1 天前
Node.js 开发上手指南:从环境搭建到实战开发
node.js
福大大架构师每日一题1 天前
dify 1.11.4 正式发布:全面强化安全性、修复多项关键问题,Node.js 升级至 24.13.0!附详细升级指南
node.js·dify
winfredzhang1 天前
从零构建:基于 Node.js 与 ECharts 的量化交易策略模拟系统
前端·node.js·echarts·股票·策略
Ashley_Amanda1 天前
Node.js 版本管理指南
node.js
摇滚侠1 天前
Node.js 安装及环境变量配置,压缩包格式的安装包
node.js
天天打码2 天前
Svelte-无虚拟DOM、极致性能的现代高性能Web开发框架!
前端·node.js·vue·svelte
吹牛不交税2 天前
win10切换node.js版本
node.js