什么是Strapi Link to heading

Strapi 是领先的开源Headless CMS。它是 100% JavaScript,完全可定制,有完善的开发文档,有现代化的管理面板且所以基础功能可视化操作,社区活跃。

Strapi特点 Link to heading

1

安装 Link to heading

环境要求 Link to heading

  1. Node.js 12.x及以上
  2. npm 6.x及以上

数据库支持 Link to heading

Database Minimum version
SQLite 3
PostgreSQL 10
MySQL 5.6
MariaDB 10.1
MongoDB 3.6

Strapi v4, MongoDB不支持

创建项目 Link to heading

  1. 终端输入以下命令
npx create-strapi-app my-project

or

yarn create strapi-app my-project
  1. 选择安装类型

    1. Quickstart(默认SQLite数据库)
    2. Custom(自定义数据库)
  2. 选择模版,选择y会出现官方的数据模版

  3. 输入项目名称

  4. 运行yarn develop运行项目(develop有热更新)

使用 Link to heading

注册并登录 Link to heading

第一次运行Strapi项目时候,会要求你注册一个账号,其实就是给当前系统添加一个超级管理员账号,注册好以后登录

2

3

创建集合(表) Link to heading

  1. 点击侧边菜单内容类型生成器,点击创建新的Content Type,填入名称

4

5

  1. 点击继续,为当前集合创建字段,字段可以选择基本属性,比如是否唯一,必填等

6

7

8

为集合添加数据 Link to heading

  1. 点击侧边菜单集合名称,点击add

9

  1. 输入数据,点击savepublish

10

用户与权限 Link to heading

Strapi 是一个headless cms,它已经内置了用户模块和权限控制模块,而为所有的操作都建立在权限系统之上。Strapi集成了两套用户权限系统,分别对应管理面板和开发者,都可以通过面板进行管理

11

你可以为每一个角色,设置不同的权限

插件 Link to heading

Strapi 是围绕不同类型的插件构建的。有核心插件对于您的 Strapi 应用程序运行至关重要,因此无法停用。但是还有其他插件,可以默认安装或不安装,为您的 Strapi 应用程序添加更多选项和可能性。

12

可以通过管理面板的插件市场安装或者通过命令方式安装

13

开发 Link to heading

API接口 Link to heading

基本API Link to heading

Method Path Description
GET /tasks Get a list of tasks
GET /tasks/:id Get a specific task
GET /tasks/count Count tasks
POST /tasks Create a task
DELETE /tasks/:id Delete a task
PUT /tasks/:id Update a task

用户注册 Link to heading

POST http://localhost:1337/auth/local/register

Request

{
  "username": "Strapi user",
  "email": "user@strapi.io",
  "password": "strapiPassword"
}

Response

{
  "id": "string",
  "username": "string",
  "email": "string",
  "provider": "string",
  "confirmed": false,
  "blocked": false,
  "role": {
    "id": "string",
    "name": "string",
    "description": "string",
    "type": "string",
    "permissions": [
      "string"
    ],
    "users": [
      "string"
    ],
    "created_by": "string",
    "updated_by": "string"
  }
}

用户登录 Link to heading

POST http://localhost:1337/auth/local

Request

{
  "identifier": "Strapi user",
  "password": "strapiPassword"
}

Response

{
  "jwt": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6MiwiaWF0IjoxNjI3ODMzMTM2LCJleHAiOjE2MzA0MjUxMzZ9.w43LtDrrZUHYWHdjZHMiTHShO6NrqfkLVqhsdTRojfw",
  "user": {
      "id": 2,
      "username": "wangyu",
      "email": "wangyu@wangyu.link",
      "provider": "local",
      "confirmed": true,
      "blocked": false,
      "role": {
          "id": 1,
          "name": "Authenticated",
          "description": "Default role given to authenticated user.",
          "type": "authenticated"
      },
      "created_at": "2021-08-01T14:40:40.600Z",
      "updated_at": "2021-08-01T14:43:28.135Z"
  }
}

token使用 Link to heading

import axios from 'axios';

const token = 'YOUR_TOKEN_HERE';

// Request API.
axios
  .get('http://localhost:1337/posts', {
    headers: {
      Authorization: `Bearer ${token}`,
    },
  })
  .then(response => {
    // Handle success.
    console.log('Data: ', response.data);
  })
  .catch(error => {
    // Handle error.
    console.log('An error occurred:', error.response);
  });

14

定制开发 Link to heading

Routing Link to heading

打开./api/task/config/routes.json,这里是当前COLLECTION路由列表,添加你想要的路由即可

{
  "routes": [
    {
      "method": "PUT",
      "path": "/tasks/update-type/:id",
      "handler": "task.updateType",
      "config": {
        "policies": ["verification"]
      }
    }
  ]
}
  • method (string): 路由请求方法 (e.g. GET, POST, PUT, HEAD, DELETE, PATCH).
  • path (string): 路径 (e.g. /restaurants).
  • handler (string): 命中路由时要进行的操作,格式 controller.action
  • config
    • policies (array): 路由守卫,在命中路由之前做的操作,例如数据验证

Policies Link to heading

创建./api/task/config/policies/verification.js,作为当前COLLECTION路由的一个守卫

module.exports = async (ctx, next) => {
  const mapData = ['online', 'offline']
  if (ctx.request.body && ctx.request.body.type && mapData.includes(ctx.request.body.type)) {
    return await next();
  } else {
    throw strapi.errors.badRequest('数据格式不正确')
  }
};

Controllers Link to heading

打开./api/task/controllers/task.js,写入一个action方法,可以自定义,可以覆盖Strapi默认的action(find findOne count create update delete)

module.exports = {
  // action
  async updateType (ctx) {
    const { id } = ctx.params;
    let entity = await strapi.services.task.update({ id }, ctx.request.body);
    strapi.services.task.send('update type success!')
    return sanitizeEntity(entity, { model: strapi.models.task });
  }
};

API:https://strapi.io/documentation/developer-docs/latest/development/backend-customization.html#controllers

services Link to heading

打开./api/task/services/task.js,可以自定义services。services应该是数据库操作或者单个的Controller逻辑

module.exports = {
  send (msg) {
    // do something
  }
};

controllers里面这样调用

module.exports = {
  async updateType (ctx) {
    // strapi是全局变量
    // strapi.services.文件名.方法名
    strapi.services.task.send('update type success!')
  }
};

API:https://strapi.io/documentation/developer-docs/latest/development/backend-customization.html#services

middlewares Link to heading

./middlewares文件夹里面新建文件夹,例如./middlewares/timer/index.js,middlewares是继承与koa的middlewares,如果你不熟悉可以看koa文档

// middlewares 建议把你的逻辑写到await next();之后
module.exports = strapi => {
  return {
    initialize() {
      strapi.app.use(async (ctx, next) => {
        await next();
        const start = Date.now();
        const delta = Math.ceil(Date.now() - start);
        ctx.set('X-Response-Time', delta + 'ms');
      });
    },
  };
};

然后需要配置middlewares执行顺序,打开./config/middlewares.js,写入以下配置。timer为第一个执行middlewares其他的是系统默认middlewares,具体解释看下面的文档。

module.exports = {
  load: {
    before: ['timer', 'responseTime', 'logger', 'cors', 'responses', 'gzip'],
    order: [
      "Define the middlewares' load order by putting their name in this array is the right order",
    ],
    after: ['parser', 'router']
  }
  //...
};

APi:https://strapi.io/documentation/developer-docs/latest/setup-deployment-guides/configurations.html#middlewares

部署 Link to heading

服务器要求

  • At least 1 CPU core (Highly recommended at least 2)
  • At least 2 GB of RAM (Moderately recommended 4)
  • Minimum required storage space recommended by your OS or 32 GB of free space
  • A supported operating system
    • Ubuntu >= 18.04 (LTS-Only)
    • Debian >= 9.x
    • CentOS/RHEL >= 8
    • macOS Mojave or newer (ARM not supported)
    • Windows 10
  1. 构建管理面板
NODE_ENV=production yarn build

or

yarn build
  1. 启动服务
NODE_ENV=production yarn start

or

yarn start

你也可以通过pm2管理进程;各大云服务厂商也提供了快速部署的方法;也提供了docker部署