Skip to content

使用 Node.js、Express 和 Sequelize 实现接口服务示例。

1. 初始化项目

首先,确保你已经安装了 Node.js 和 npm。然后按照以下步骤初始化项目:

bash
mkdir my-express-sequelize-app
cd my-express-sequelize-app
npm init -y

安装必要的依赖:

bash
npm install express sequelize mysql2

如果你需要使用其他数据库(如 PostgreSQL 或 SQLite),请安装对应的驱动程序。例如,PostgreSQL 需要 pg

bash
npm install pg

2. 创建项目结构

创建以下文件和文件夹:

my-express-sequelize-app/
├── config/
│   └── config.js
├── models/
│   └── user.js
├── routes/
│   └── users.js
├── app.js
└── server.js

3. 配置数据库

config/config.js

javascript
module.exports = {
  development: {
    dialect: 'mysql', // 或者 'postgres', 'sqlite' 等
    host: 'localhost',
    username: 'root',
    password: '',
    database: 'my_database',
    port: 3306,
  },
  production: {
    dialect: 'mysql',
    host: 'localhost',
    username: 'root',
    password: '',
    database: 'my_database',
    port: 3306,
  },
};

4. 定义模型

models/user.js

javascript
const { Sequelize, DataTypes } = require('sequelize');

module.exports = (sequelize) => {
  const User = sequelize.define('User', {
    name: {
      type: DataTypes.STRING,
      allowNull: false,
    },
    email: {
      type: DataTypes.STRING,
      allowNull: false,
      unique: true,
    },
    age: {
      type: DataTypes.INTEGER,
    },
  });

  return User;
};

5. 创建路由

routes/users.js

javascript
const express = require('express');
const router = express.Router();
const { User } = require('../models');

// 获取所有用户
router.get('/', async (req, res) => {
  try {
    const users = await User.findAll();
    res.json(users);
  } catch (error) {
    res.status(500).json({ error: error.message });
  }
});

// 创建新用户
router.post('/', async (req, res) => {
  try {
    const user = await User.create(req.body);
    res.status(201).json(user);
  } catch (error) {
    res.status(500).json({ error: error.message });
  }
});

// 获取单个用户
router.get('/:id', async (req, res) => {
  try {
    const user = await User.findByPk(req.params.id);
    if (user) {
      res.json(user);
    } else {
      res.status(404).json({ message: 'User not found' });
    }
  } catch (error) {
    res.status(500).json({ error: error.message });
  }
});

// 更新用户
router.put('/:id', async (req, res) => {
  try {
    const user = await User.findByPk(req.params.id);
    if (user) {
      await user.update(req.body);
      res.json(user);
    } else {
      res.status(404).json({ message: 'User not found' });
    }
  } catch (error) {
    res.status(500).json({ error: error.message });
  }
});

// 删除用户
router.delete('/:id', async (req, res) => {
  try {
    const user = await User.findByPk(req.params.id);
    if (user) {
      await user.destroy();
      res.json({ message: 'User deleted successfully' });
    } else {
      res.status(404).json({ message: 'User not found' });
    }
  } catch (error) {
    res.status(500).json({ error: error.message });
  }
});

module.exports = router;

6. 创建主应用文件

app.js

javascript
const express = require('express');
const bodyParser = require('body-parser');
const { Sequelize } = require('sequelize');
const config = require('./config/config');
const userRouter = require('./routes/users');
const User = require('./models/user');

const app = express();

// 解析 JSON 请求体
app.use(bodyParser.json());

// 初始化 Sequelize
const sequelize = new Sequelize(config.development);

// 同步数据库模型
sequelize.sync().then(() => {
  console.log('Database synchronized');
});

// 注册路由
app.use('/api/users', userRouter);

module.exports = app;

7. 创建服务器文件

server.js

javascript
const app = require('./app');

const PORT = process.env.PORT || 3000;

app.listen(PORT, () => {
  console.log(`Server is running on http://localhost:${PORT}`);
});

8. 启动项目

运行以下命令启动服务器:

bash
node server.js

9. 测试接口

你可以使用工具如 Postmancurl 测试接口。

示例请求:

  • 获取所有用户

    bash
    GET http://localhost:3000/api/users
  • 创建新用户

    bash
    POST http://localhost:3000/api/users
    Content-Type: application/json
    
    {
      "name": "John Doe",
      "email": "john.doe@example.com",
      "age": 30
    }
  • 获取单个用户

    bash
    GET http://localhost:3000/api/users/1
  • 更新用户

    bash
    PUT http://localhost:3000/api/users/1
    Content-Type: application/json
    
    {
      "name": "John Doe Updated",
      "email": "john.doe.updated@example.com"
    }
  • 删除用户

    bash
    DELETE http://localhost:3000/api/users/1

10. 其他功能扩展

你可以根据需求扩展以下功能:

  • 添加身份验证和授权(如 JWT)
  • 添加分页功能
  • 添加错误日志记录
  • 添加单元测试

通过以上步骤,你就可以使用 Express 和 Sequelize 创建一个简单的 RESTful API 服务。