当前位置:首页 > CMS教程 > Thinkphp > 列表

ThinkPHP 5 AJAX跨域请求头设置实现过程解析

发布:smiling 来源: PHP粉丝网  添加日期:2022-03-29 08:55:35 浏览: 评论:0 

最近用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.   public function run(&$dispatch){ 
  16.     $host_name = isset($_SERVER['HTTP_ORIGIN']) ? $_SERVER['HTTP_ORIGIN'] : "*"
  17.     $headers = [ 
  18.       "Access-Control-Allow-Origin" => $host_name
  19.       "Access-Control-Allow-Credentials" => 'true'
  20.       "Access-Control-Allow-Headers" => "x-token,x-uid,x-token-check,x-requested-with,content-type,Host" 
  21.     ]; 
  22.     if($dispatch instanceof Response) { 
  23.       $dispatch->header($headers); 
  24.     } else if($_SERVER['REQUEST_METHOD'] === 'OPTIONS') { 
  25.       $dispatch['type'] = 'response'
  26.       $response = new Response('', 200, $headers); 
  27.       $dispatch['response'] = $response
  28.     } 
  29.   } 

接着在项目中(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 <liu21st@gmail.com> 
  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. ]; 

ok,以上几步就解决跨域请求问题。

Tags: ThinkPHP5跨域请求头设置

分享到: