最近用thinkphp做項目,在測試環(huán)境時,存在接口的測試問題。在tp官網(wǎng)也沒能找到相關(guān)的解決方法。自已看了一下源碼,有如下的解決方案。
在項目目錄下面,創(chuàng)建common/behavior/CronRun.php文件,文件內(nèi)容如下:
?php
/**
* Created by PhpStorm.
* User: LiuYang
* Date: 2017/3/9
* Time: 19:37
*/
namespace app\common\behavior;
use think\Exception;
use think\Response;
class CronRun
{
public function run($dispatch){
$host_name = isset($_SERVER['HTTP_ORIGIN']) ? $_SERVER['HTTP_ORIGIN'] : "*";
$headers = [
"Access-Control-Allow-Origin" => $host_name,
"Access-Control-Allow-Credentials" => 'true',
"Access-Control-Allow-Headers" => "x-token,x-uid,x-token-check,x-requested-with,content-type,Host"
];
if($dispatch instanceof Response) {
$dispatch->header($headers);
} else if($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
$dispatch['type'] = 'response';
$response = new Response('', 200, $headers);
$dispatch['response'] = $response;
}
}
}
接著在項目中(tags.php)配置行為動作,如下:
?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006~2016 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st liu21st@gmail.com>
// +----------------------------------------------------------------------
// 應用行為擴展定義文件
return [
// 應用初始化
'app_init' => [],
// 應用開始
'app_begin' => [
'app\\common\\behavior\\CronRun'
],
// 模塊初始化
'module_init' => [],
// 操作開始執(zhí)行
'action_begin' => [],
// 視圖內(nèi)容過濾
'view_filter' => [],
// 日志寫入
'log_write' => [],
// 應用結(jié)束
'app_end' => [
'app\\common\\behavior\\CronRun'
],
];
ok,以上幾步就解決跨域請求問題。
以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
您可能感興趣的文章:- PHP Ajax跨域問題解決方案代碼實例
- 原生js實現(xiàn)ajax請求和JSONP跨域請求操作示例
- PHP下ajax跨域的解決方案之window.name實例分析
- PHP下ajax跨域的解決方案之jsonp實例分析
- 使用ajax跨域調(diào)用springboot框架的api傳輸文件
- express如何解決ajax跨域訪問session失效問題詳解
- Ajax跨域問題及解決方案(jsonp,cors)
- Ajax解決跨域之設(shè)置CORS響應頭實現(xiàn)跨域案例詳解