关于代码分离可能会遇到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啦!