返回

Egg.js 前后端分离实战: 实现文章增删改查

前端

1. 项目初始化

首先,我们创建一个新的 Egg.js 项目:

mkdir my-app && cd my-app
npm init egg

2. 安装依赖

接下来,我们需要安装一些必要的依赖:

npm install --save egg-mysql
npm install --save egg-sequelize

其中,egg-mysql 是 Egg.js 的 MySQL 插件,egg-sequelize 是 Egg.js 的 Sequelize 插件。

3. 配置数据库

在 config/config.default.js 中,我们配置数据库:

module.exports = {
  // ...
  sequelize: {
    dialect: 'mysql',
    host: '127.0.0.1',
    port: 3306,
    database: 'my-app',
    username: 'root',
    password: 'password',
  },
  // ...
};

4. 定义模型

在 app/model/article.js 中,我们定义文章模型:

module.exports = app => {
  const { STRING, TEXT, INTEGER, DATE } = app.Sequelize;

  return app.model.define('article', {
    id: {
      type: INTEGER,
      primaryKey: true,
      autoIncrement: true,
    },
    title: {
      type: STRING,
      allowNull: false,
    },
    content: {
      type: TEXT,
      allowNull: false,
    },
    author: {
      type: STRING,
      allowNull: false,
    },
    createdAt: {
      type: DATE,
      allowNull: false,
    },
    updatedAt: {
      type: DATE,
      allowNull: false,
    },
  });
};

5. 定义路由

在 app/router.js 中,我们定义路由:

module.exports = app => {
  const { controller } = app;

  app.router.get('/articles', controller.article.index);
  app.router.post('/articles', controller.article.create);
  app.router.get('/articles/:id', controller.article.show);
  app.router.put('/articles/:id', controller.article.update);
  app.router.delete('/articles/:id', controller.article.destroy);
};

6. 定义控制器

在 app/controller/article.js 中,我们定义控制器:

module.exports = app => {
  const { Op } = app.Sequelize;

  class ArticleController extends app.Controller {
    async index() {
      const { ctx } = this;

      const articles = await ctx.model.Article.findAll();

      ctx.body = articles;
    }

    async create() {
      const { ctx } = this;

      const article = await ctx.model.Article.create(ctx.request.body);

      ctx.body = article;
    }

    async show() {
      const { ctx } = this;

      const article = await ctx.model.Article.findByPk(ctx.params.id);

      if (!article) {
        ctx.throw(404, '文章不存在');
      }

      ctx.body = article;
    }

    async update() {
      const { ctx } = this;

      const article = await ctx.model.Article.findByPk(ctx.params.id);

      if (!article) {
        ctx.throw(404, '文章不存在');
      }

      await article.update(ctx.request.body);

      ctx.body = article;
    }

    async destroy() {
      const { ctx } = this;

      const article = await ctx.model.Article.findByPk(ctx.params.id);

      if (!article) {
        ctx.throw(404, '文章不存在');
      }

      await article.destroy();

      ctx.body = {
        success: true,
      };
    }
  }

  return ArticleController;
};

7. 启动应用

最后,我们可以启动应用:

npm run dev

8. 测试

现在,我们可以使用 Postman 或其他工具来测试我们的 API:

  • 获取所有文章:
GET http://localhost:7001/articles
  • 创建一篇新文章:
POST http://localhost:7001/articles
{
  "title": "我的第一篇文章",
  "content": "这是一篇关于 Egg.js 的文章",
  "author": "张三"
}
  • 获取一篇指定的文章:
GET http://localhost:7001/articles/1
  • 更新一篇指定的文章:
PUT http://localhost:7001/articles/1
{
  "title": "我的第一篇文章(已更新)",
  "content": "这是一篇关于 Egg.js 的文章(已更新)",
  "author": "李四"
}
  • 删除一篇指定的文章:
DELETE http://localhost:7001/articles/1

9. 总结

在本教程中,我们学习了如何使用 Egg.js 来构建一个简单的文章增删改查应用。我们还学习了如何实现前后端分离。希望这篇教程对你有帮助。