客户端发送GET或POST之前,
可能会先发送OPTION请求,以查询服务是否支持跨域。所以thinkphp需要做两样事:
1、响应OPTION请求支持跨域。
2、响应实际的GET/POST请求支持跨域。
在public\index.php开始地方添加:
if($_SERVER['REQUEST_METHOD'] == 'OPTIONS') { header("Access-Control-Allow-Origin: *"); header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept, Authorization"); header('Access-Control-Allow-Methods: GET, POST, PUT,DELETE,OPTIONS,PATCH'); exit(); }
在public\index.php最后地方添加:
header("Access-Control-Allow-Origin: *"); header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept, Authorization"); header('Access-Control-Allow-Methods: GET, POST, PUT,DELETE,OPTIONS,PATCH');
最后整个public\index.php代码:
<?php // +---------------------------------------------------------------------- // | ThinkPHP [ WE CAN DO IT JUST THINK ] // +---------------------------------------------------------------------- // | Copyright (c) 2006-2018 http://thinkphp.cn All rights reserved. // +---------------------------------------------------------------------- // | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 ) // +---------------------------------------------------------------------- // | Author: liu21st <liu21st@gmail.com> // +---------------------------------------------------------------------- // [ 应用入口文件 ] namespace think; // OPTION请求支持跨域 if($_SERVER['REQUEST_METHOD'] == 'OPTIONS') { header("Access-Control-Allow-Origin: *"); header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept, Authorization"); header('Access-Control-Allow-Methods: GET, POST, PUT,DELETE,OPTIONS,PATCH'); exit(); } // 加载基础文件 require __DIR__ . '/../thinkphp/base.php'; // 支持事先使用静态方法设置Request对象和Config对象 // 执行应用并响应 Container::get('app')->run()->send(); // GET POST请求支持跨域 header("Access-Control-Allow-Origin: *"); header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept, Authorization"); header('Access-Control-Allow-Methods: GET, POST, PUT,DELETE,OPTIONS,PATCH');