Base.php 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  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. protected function _initialize()
  21. {
  22. (new WebService())->checkInstalled();
  23. header('Access-Control-Allow-Origin: *');//允许跨域,*星号表示所有的域都可以接受
  24. header('Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept, x-token');//允许访问的header
  25. }
  26. /**
  27. * api成功的响应
  28. * @param $msg string 成功消息
  29. * @param $data null 响应数据
  30. * @param $err_code int 消息码
  31. */
  32. protected function json_success($msg = "success", $data = null, $err_code = 0)
  33. {
  34. //和success方法相比,没有显示跳转页面,直接响应了json
  35. //和success方法返回的code要一致,这样前端ajax不用修改就能兼容
  36. $result = [
  37. 'code' => 1,
  38. 'err_code' => $err_code,
  39. 'msg' => $msg,
  40. 'time' => Request::instance()->server('REQUEST_TIME'),
  41. 'data' => $data,
  42. ];
  43. throw new HttpResponseException(json($result));
  44. }
  45. /**
  46. * api失败的响应
  47. * @param $msg string 错误消息
  48. * @param null $data 响应数据
  49. * @param $err_code int 消息码
  50. */
  51. protected function json_error($msg = "error", $data = null, $err_code = 0)
  52. {
  53. $result = [
  54. 'code' => 0,
  55. 'err_code' => $err_code,
  56. 'msg' => $msg,
  57. 'time' => Request::instance()->server('REQUEST_TIME'),
  58. 'data' => $data,
  59. ];
  60. throw new HttpResponseException(json($result));
  61. }
  62. }