vue 与thinkphp跨域

原因

1、浏览器限制

2、跨域(域名,端口不一样都是跨域)

3、XHR(XMLHttpRequest请求)

同时满足三个条件才有可能产生跨域问题。

>利用钩子函数解决

1.在app\common\behavior\CORS

代码语言:javascript
复制
<?php
namespace app\common\behavior;
use think\Request;
use think\Response;

/**
 * ${PARAM_DOC}
 * @return ${TYPE_HINT}
 * ${THROWS_DOC}
 * Date: 2021/3/24 18:01
 */
class CORS{
    public function run()
    {
        // 响应头设置 我们就是通过设置header来跨域的 这就主要代码了 定义行为只是为了前台每次请求都能走这段代码
        $host_name = isset($_SERVER['HTTP_ORIGIN']) ? $_SERVER['HTTP_ORIGIN'] : "*";
        header("Access-Control-Allow-Origin:*");
        header('Access-Control-Allow-Headers: content-type,token');
        header('Access-Control-Allow-Methods:*');
        header('Access-Control-Allow-Headers:token,Origin,X-Requested-With,Content-Type,content-type,Accept,Authorized-Token,Authori-zation,Authorization,authorized-token,If-Match, If-Modified-Since, If-None-Match, If-Unmodified-Since');
        header('Access-Control-Allow-Credentials:false');
        if (request()->isOptions()) {
            exit();
        }
    }
}

2.将tags.php

代码语言:javascript
复制
return [
// 应用初始化
&#39;app_init&#39;     =&gt; [],
// 应用开始
&#39;app_begin&#39;    =&gt; [
    &#39;app\\common\\behavior\\CORS&#39;
],
// 模块初始化
&#39;module_init&#39;  =&gt; [],
// 操作开始执行
&#39;action_begin&#39; =&gt; [],
// 视图内容过滤
&#39;view_filter&#39;  =&gt; [],
// 日志写入
&#39;log_write&#39;    =&gt; [],
// 应用结束
&#39;app_end&#39;      =&gt; [
    &#39;app\\common\\behavior\\CORS&#39;
],

];

常见解决方法

代码语言:javascript
复制
if($_SERVER['REQUEST_METHOD'] == 'OPTIONS'){
header('Access-Control-Allow-Headers: content-type,token');
//允许的源域名
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;
}