CORS 跨站设置

使用CORS中间定义跨站的请求策略,你需要在主配置或对应的模块下创建配置 config/cors.php,例如:

  1. return [
  2. 'allow_origin' => [
  3. 'http://localhost:3000',
  4. ],
  5. 'allow_credentials' => false,
  6. 'allow_methods' => ['GET', 'OPTIONS', 'POST', 'PUT'],
  7. 'expose_headers' => [],
  8. 'allow_headers' => ['Content-Type', 'X-Requested-With', 'X-Token'],
  9. 'max_age' => 0,
  10. ];
  • allow_origin array 允许访问该资源的外域 URI,对于不需要携带身份凭证的请求,服务器可以指定该字段的值为通配符 ['*']
  • allow_credentials boolean 允许浏览器读取response的内容
  • expose_headers array 允许浏览器访问的头放入白名单
  • allow_headers string 允许携带的首部字段
  • allow_methods array 允许使用的 HTTP 方法
  • max_age int preflight请求的结果能够被缓存多久

注册中间件 config/middleware.php

  1. return [
  2. 'cors' => \think\bit\middleware\Cors::class
  3. ];

在控制器中引入

  1. abstract class BaseController
  2. {
  3. protected $middleware = ['cors'];
  4. }

Auth 鉴权验证

AuthVerify 鉴权验证是一个抽象定义中间件,使用时需要根据场景继承定义,例如

  1. class SystemAuthVerify extends AuthVerify
  2. {
  3. protected $scene = 'system';
  4. protected function hook(stdClass $symbol): bool
  5. {
  6. $data = AdminRedis::create()->get($symbol->user);
  7. if (empty($data)) {
  8. $this->hookResult = [
  9. 'error' => 1,
  10. 'msg' => 'freeze'
  11. ];
  12. return false;
  13. }
  14. return true;
  15. }
  16. }
  • scene string 场景标签
  • hook(stdClass $symbol): bool 中间件钩子

然后在将中间件注册在应用的 middleware.php 配置下

  1. return [
  2. 'auth' => \app\system\middleware\SystemAuthVerify::class
  3. ];

在控制器中重写 $middleware

  1. namespace app\system\controller;
  2. class Index extends BaseController
  3. {
  4. protected $middleware = ['auth'];
  5. public function index()
  6. {
  7. return [];
  8. }
  9. }

全局返回 JSON

强制响应为 JSON,省略每个 Action 都要设置响应输出,首先加入 middleware.php

  1. return [
  2. 'json' => \think\bit\middleware\JsonResponse::class,
  3. ];

在控制器中重写 $middleware

  1. namespace app\index\controller;
  2. use app\index\BaseController;
  3. class Index extends BaseController
  4. {
  5. protected $middleware = ['json'];
  6. public function index()
  7. {
  8. return [];
  9. }
  10. }

过滤 POST 请求

将 Restful API 请求全局统一为 POST 类型,首先加入 middleware.php

  1. return [
  2. 'post' => \think\bit\middleware\FilterPostRequest::class,
  3. ];

在控制器中重写 $middleware

  1. namespace app\index\controller;
  2. use app\index\BaseController;
  3. class Index extends BaseController
  4. {
  5. protected $middleware = ['post'];
  6. public function index()
  7. {
  8. return [];
  9. }
  10. }