Base.php 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. <?php
  2. /**
  3. * Created by PhpStorm.
  4. * User: 中闽 < 1464674022@qq.com >
  5. * Date: 2019/12/5
  6. * Time: 17:44
  7. */
  8. namespace app\api\controller\base;
  9. use app\common\service\WebService;
  10. use think\Controller;
  11. use think\exception\HttpResponseException;
  12. use think\Request;
  13. /**
  14. * 接口父类
  15. * Class
  16. * @package app\api\controller\base
  17. */
  18. class Base extends Controller
  19. {
  20. const ERR_CODE_LOGIN = 1;
  21. protected function _initialize()
  22. {
  23. (new WebService())->checkInstalled();
  24. header('Access-Control-Allow-Origin: *');//允许跨域,*星号表示所有的域都可以接受
  25. header('Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept, x-token');//允许访问的header
  26. }
  27. /**
  28. * api成功的响应
  29. * @param $msg string 成功消息
  30. * @param $data null 响应数据
  31. * @param $err_code int 消息码
  32. */
  33. protected function json_success($msg = "success", $data = null, $err_code = 0)
  34. {
  35. //和success方法相比,没有显示跳转页面,直接响应了json
  36. //和success方法返回的code要一致,这样前端ajax不用修改就能兼容
  37. $result = [
  38. 'code' => 1,
  39. 'err_code' => $err_code,
  40. 'msg' => $msg,
  41. 'time' => Request::instance()->server('REQUEST_TIME'),
  42. 'data' => $data,
  43. ];
  44. throw new HttpResponseException(json($result));
  45. }
  46. /**
  47. * api失败的响应
  48. * @param $msg string 错误消息
  49. * @param null $data 响应数据
  50. * @param $err_code int 消息码
  51. */
  52. protected function json_error($msg = "error", $data = null, $err_code = 0)
  53. {
  54. $result = [
  55. 'code' => 0,
  56. 'err_code' => $err_code,
  57. 'msg' => $msg,
  58. 'time' => Request::instance()->server('REQUEST_TIME'),
  59. 'data' => $data,
  60. ];
  61. throw new HttpResponseException(json($result));
  62. }
  63. }