JavaScript通过Node.js进行后端开发指南

1. 基础环境搭建

1.1 安装Node.js

node -v  # 检查Node.js版本
npm -v   # 检查npm版本

1.2 初始化项目

mkdir my-backend
cd my-backend
npm init -y  # 生成package.json

2. 创建HTTP服务器

2.1 原生http模块(基础示例)

// server.js
const http = require('http');

const server = http.createServer((req, res) => {
  res.writeHead(200, { 'Content-Type': 'text/plain' });
  res.end('Hello from Node.js!');
});

server.listen(3000, () => {
  console.log('Server running at http://localhost:3000');
});

运行:node server.js

2.2 使用Express框架(推荐)

安装Express:

npm install express

示例代码:

// app.js
const express = require('express');
const app = express();

app.get('/', (req, res) => {
  res.send('Hello from Express!');
});

app.listen(3000, () => {
  console.log('Express server running on port 3000');
});

3. 核心功能实现

3.1 路由处理

// 获取查询参数(如 /search?q=nodejs)
app.get('/search', (req, res) => {
  const query = req.query.q;
  res.send(`Searching for: ${query}`);
});

// 动态路由参数(如 /users/123)
app.get('/users/:id', (req, res) => {
  res.send(`User ID: ${req.params.id}`);
});

// POST请求处理
app.post('/users', express.json(), (req, res) => {
  const userData = req.body;
  res.status(201).json({ id: 1, ...userData });
});

3.2 中间件(Middleware)

// 日志中间件
app.use((req, res, next) => {
  console.log(`${req.method} ${req.url}`);
  next();
});

// 静态文件托管
app.use(express.static('public'));  // 访问 http://localhost:3000/image.jpg

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

4. 数据库集成

4.1 MongoDB(NoSQL)

安装Mongoose:

npm install mongoose

示例代码:

const mongoose = require('mongoose');

// 连接数据库
mongoose.connect('mongodb://localhost:27017/mydb');

// 定义数据模型
const User = mongoose.model('User', {
  name: String,
  email: { type: String, unique: true }
});

// 创建用户
app.post('/users', async (req, res) => {
  try {
    const user = new User(req.body);
    await user.save();
    res.status(201).json(user);
  } catch (err) {
    res.status(400).json({ error: err.message });
  }
});

4.2 MySQL(SQL)

安装mysql2

npm install mysql2

示例代码:

const mysql = require('mysql2/promise');

// 创建连接池
const pool = mysql.createPool({
  host: 'localhost',
  user: 'root',
  password: 'yourpassword',
  database: 'test'
});

// 查询示例
app.get('/products', async (req, res) => {
  const [rows] = await pool.query('SELECT * FROM products');
  res.json(rows);
});

5. 用户认证(JWT)

安装依赖:

npm install jsonwebtoken bcryptjs

示例代码:

const jwt = require('jsonwebtoken');
const bcrypt = require('bcryptjs');

// 模拟用户数据库
const users = [];

// 注册
app.post('/register', async (req, res) => {
  const hashedPassword = await bcrypt.hash(req.body.password, 10);
  users.push({
    username: req.body.username,
    password: hashedPassword
  });
  res.status(201).send('User registered');
});

// 登录
app.post('/login', async (req, res) => {
  const user = users.find(u => u.username === req.body.username);
  if (!user || !await bcrypt.compare(req.body.password, user.password)) {
    return res.status(401).send('Invalid credentials');
  }

  const token = jwt.sign({ username: user.username }, 'your-secret-key', {
    expiresIn: '1h'
  });
  res.json({ token });
});

// 受保护的路由
app.get('/profile', (req, res) => {
  const token = req.headers.authorization?.split(' ')[1];
  if (!token) return res.status(401).send('Unauthorized');

  try {
    const decoded = jwt.verify(token, 'your-secret-key');
    res.send(`Welcome, ${decoded.username}`);
  } catch (err) {
    res.status(401).send('Invalid token');
  }
});

6. 部署上线

6.1 使用PM2(进程管理)

安装:

npm install pm2 -g

启动服务:

pm2 start app.js --name "my-api"

常用命令:

pm2 logs       # 查看日志
pm2 restart all # 重启服务

6.2 Docker容器化

创建Dockerfile

FROM node:18
WORKDIR /app
COPY package*.json ./
RUN npm install
COPY . .
EXPOSE 3000
CMD ["node", "app.js"]

构建并运行:

docker build -t node-app .
docker run -p 3000:3000 node-app

项目结构建议

node-backend/
├── src/
│   ├── controllers/  # 业务逻辑
│   ├── models/       # 数据库模型
│   ├── routes/       # 路由定义
│   ├── middleware/   # 中间件
│   └── app.js        # 入口文件
├── .env              # 环境变量
├── package.json
└── README.md

总结

  1. 基础服务:用httpExpress创建服务器
  2. 路由与中间件:处理请求、静态文件和日志
  3. 数据库:集成MongoDB或MySQL
  4. 安全:JWT认证和密码加密
  5. 部署:通过PM2或Docker上线

按照以上步骤,你可以快速构建一个完整的Node.js后端服务!

以上来自Juleon博客,转载请注明出处。