Thinkphp5跨域問題

關於代碼分離可能會遇到json傳輸接收不到的問題(可能00)

起初我百度到解決此問題能夠用jsonp來發送並接受,但是這只是一時之計 之後也會不方便因此我發現了一下方法

在app頂層建立文件common\behavior\CronRun.php 寫入如下代碼

 1 <?php
 2 /**
 3  * Created by PhpStorm.
 4  * User: qianglong
 5  * Date: 2018/1/15
 6  * Time: 17:56
 7  */
 8 namespace app\common\behavior;
 9  
10 use think\Exception;
11 use think\Response;
12  
13 class CronRun
14 {
15     public function run(&$dispatch){
16         header("Access-Control-Allow-Origin:*");
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 }

添加鉤子事件

在application \tags下寫入

<?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'  => [],
    // 操做開始執行
    'action_begin' => [],
    // 視圖內容過濾
    'view_filter'  => [],
    // 日誌寫入
    'log_write'    => [],
    // 應用結束
    'app_end'      => [
        'app\\common\\behavior\\CronRun'
    ],
];

這樣就能跨域請求api啦!

相關文章
相關標籤/搜索
本站公眾號
   歡迎關注本站公眾號,獲取更多信息