Access-Control-Allow-Origin
完整报错
Access to XMLHttpRequest at ‘http://xxx.xxx.xxx/api/ip’ from origin ‘null’ has been blocked by CORS policy: No ‘Access-Control-Allow-Origin’ header is present on the requested resource.
解决(php)
单文件
如果不是用php框架,而是用原生写,在文件开头<?php
之后加入header("Access-Control-Allow-Origin:*");
就行了。
tp6
找到/tp5/app/BaseController.php这个文件,在初始化加下面这段就行了
// 初始化
protected function initialize()
{
header("Access-Control-Allow-Origin:*");
header("Access-Control-Allow-Methods:GET, POST, OPTIONS, DELETE");
header("Access-Control-Allow-Headers:DNT,X-Mx-ReqToken,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type, Accept-Language, Origin, Accept-Encoding");
}
tp5
由于tp5没有默认应用文件,
所以找到tp5\application\index\controller文件夹,在里面创建一个PHP文件,加入下列代码
protected function initialize()
{
//跨域
parent::initialize(); // TODO: Change the autogenerated stub
header('Access-Control-Allow-Origin:*');
header('Access-Control-Allow-Methods:GET, POST, OPTIONS, DELETE, PUT');
header('Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, token, Accept, x-access-sign, x-access-time');
}
然后,其他需要跨域文件extends创建的这个文件。
更暴力无脑的方法
找到tp5\public\index.php,加入
<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2019 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------
// [ 应用入口文件 ]
namespace think;
require __DIR__ . '/../vendor/autoload.php';
// 解决跨域问题
header("Access-Control-Allow-Origin:*");
header("Access-Control-Allow-Methods:GET, POST, OPTIONS, DELETE");
header("Access-Control-Allow-Headers:DNT,X-Mx-ReqToken,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type, Accept-Language, Origin, Accept-Encoding");
// 执行HTTP应用并响应
$http = (new App())->http;
$response = $http->run();
$response->send();
$http->end($response);