ThinkPHP 5 中AJAX跨域请求头设置方法

最近用thinkphp做项目,在测试环境时,存在接口的测试问题。在tp官网也没能找到相关的解决方法。自已看了一下源码,有如下的解决方案。

在项目目录下面,创建common/behavior/CronRun.php文件,文件内容如下:

复制

 
  1. <?php
  2. /**
  3. * Created by PhpStorm.
  4. * User: LiuYang
  5. * Date: 2017/3/9
  6. * Time: 19:37
  7. */
  8.  
  9. namespace app\common\behavior;
  10.  
  11. use think\Exception;
  12. use think\Response;
  13.  
  14. class CronRun
  15. {
  16. public function run(&$dispatch){
  17. $host_name = isset($_SERVER['HTTP_ORIGIN']) ? $_SERVER['HTTP_ORIGIN'] : "*";
  18. $headers = [
  19. "Access-Control-Allow-Origin" => $host_name,
  20. "Access-Control-Allow-Credentials" => 'true',
  21. "Access-Control-Allow-Headers" => "x-token,x-uid,x-token-check,x-requested-with,content-type,Host"
  22. ];
  23. if($dispatch instanceof Response) {
  24. $dispatch->header($headers);
  25. } else if($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
  26. $dispatch['type'] = 'response';
  27. $response = new Response('', 200, $headers);
  28. $dispatch['response'] = $response;
  29. }
  30. }
  31. }

接着在项目中(tags.php)配置行为动作,如下:

复制

 
  1. <?php
  2. // +----------------------------------------------------------------------
  3. // | ThinkPHP [ WE CAN DO IT JUST THINK ]
  4. // +----------------------------------------------------------------------
  5. // | Copyright (c) 2006~2016 http://thinkphp.cn All rights reserved.
  6. // +----------------------------------------------------------------------
  7. // | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
  8. // +----------------------------------------------------------------------
  9. // | Author: liu21st <[email protected]>
  10. // +----------------------------------------------------------------------
  11.  
  12. // 应用行为扩展定义文件
  13. return [
  14. // 应用初始化
  15. 'app_init' => [],
  16. // 应用开始
  17. 'app_begin' => [
  18. 'app\\common\\behavior\\CronRun'
  19. ],
  20. // 模块初始化
  21. 'module_init' => [],
  22. // 操作开始执行
  23. 'action_begin' => [],
  24. // 视图内容过滤
  25. 'view_filter' => [],
  26. // 日志写入
  27. 'log_write' => [],
  28. // 应用结束
  29. 'app_end' => [
  30. 'app\\common\\behavior\\CronRun'
  31. ],
  32. ];

猜你喜欢

转载自blog.csdn.net/aa19891204/article/details/81115674