• TP6自带的跨域中间件无法使用的个人解决方法


    使用TP6,因为需要跨域上传图片,一直不成功,网上搜了好久,方法都没解决跨域上传文件

    比如下面的方式没成功

    $this->app     = $app;
    $this->request = $this->app->request;
    
    // 支持跨域请求的host数组['a.cn', 'b.cn']
    $corsHost = config('mysite.cors_host');
    
    if (!empty($corsHost) && is_array($corsHost) && in_array($this->request->host(), $corsHost)) {
    
        header("access-control-allow-headers: Accept,Authorization,Cache-Control,Content-Type,DNT,If-Modified-Since,Keep-Alive,Origin,User-Agent,X-Mx-ReqToken,X-Requested-With");
        header("access-control-allow-methods: GET, POST, PUT, DELETE, HEAD, OPTIONS");
        header("access-control-allow-credentials: true");
        header('Access-Control-Allow-Origin: ' . $this->request->domain());
    }
    
    if($this->request->isOptions()) {
        exit;
    }

    发现 问题出在 $this->request->domain() ,返回的结果一直是请求地址,

    比如 a.cn跨域访问b.cn的资源, $this->request->domain() 值为 b.cn ,但是Access-Control-Allow-Origin需要返回的是a.cn

    最后只能这样了

    $this->app     = $app;
    $this->request = $this->app->request;
    
    // 支持跨域请求的host数组['a.cn', 'b.cn']
    $corsHost = config('mysite.cors_host');
    
    if (!empty($corsHost) && is_array($corsHost) && isset($_SERVER['HTTP_ORIGIN']) && in_array(parse_url($_SERVER['HTTP_ORIGIN'], PHP_URL_HOST), $corsHost)) {
    
        header("access-control-allow-headers: Accept,Authorization,Cache-Control,Content-Type,DNT,If-Modified-Since,Keep-Alive,Origin,User-Agent,X-Mx-ReqToken,X-Requested-With");
        header("access-control-allow-methods: GET, POST, PUT, DELETE, HEAD, OPTIONS");
        header("access-control-allow-credentials: true");
    //            header('Access-Control-Allow-Origin: ' . $this->request->domain());
        header('Access-Control-Allow-Origin: ' . $_SERVER['HTTP_ORIGIN']);
    }
    
    if($this->request->isOptions()) {
        exit;
    }
  • 相关阅读:
    ABP
    妖道角
    检测空值,以及会不会出现mapping类型不一致的问题
    wcf服务契约代理链
    wcf服务契约继承
    win64+anaconda+xgboost(转)
    python中迭代问题
    ROC曲线和AUC值(转)
    python中split()和split(' ')的区别
    str和repr的区别(转)
  • 原文地址:https://www.cnblogs.com/init-007/p/13352896.html
Copyright © 2020-2023  润新知