thinkphp6解决跨域

写一个前后端分离的项目 解决thinkphp6跨域问题

在这里可以使用tp6的前置中间件

第一开启中间件的文件配置

thinkphp6解决跨域

然后创建一个中间件文件

thinkphp6解决跨域

最后配置

<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2021/4/9
 * Time: 17:51
 */
declare (strict_types = 1);

namespace appmiddleware;

use Closure;
use thinkConfig;
use thinkRequest;
use thinkResponse;

class AllowCrossDomain
{

    protected $cookieDomain;

    // header头配置
    protected $header = [
         Access-Control-Allow-Credentials  =>  true ,
         Access-Control-Max-Age            => 1800,
         Access-Control-Allow-Methods      =>  GET, POST, PATCH, PUT, DELETE, OPTIONS ,
         Access-Control-Allow-Headers      =>  Authorization, Content-Type, If-Match, If-Modified-Since, If-None-Match, If-Unmodified-Since, X-CSRF-TOKEN, X-Requested-With,token ,
    ];


    /**
     * AllowCrossDomain constructor.
     * @param Config $config
     */
    public function __construct(Config $config)
    {
        $this->cookieDomain = $config->get( cookie.domain ,   );
    }

    /**
     * 允许跨域请求
     * @access public
     * @param Request $request
     * @param Closure $next
     * @param array   $header
     * @return Response
     */
    public function handle($request, Closure $next, ?array $header = [])
    {
        $header = !empty($header) ? array_merge($this->header, $header) : $this->header;

        if (!isset($header[ Access-Control-Allow-Origin ])) {
            $origin = $request->header( origin );

            if ($origin && (   == $this->cookieDomain || strpos($origin, $this->cookieDomain))) {
                $header[ Access-Control-Allow-Origin ] = $origin;
            } else {
                $header[ Access-Control-Allow-Origin ] =  * ;
            }
        }

        return $next($request)->header($header);
    }
}

© 版权声明
THE END
如果内容对您有所帮助,就支持一下吧!
点赞0 分享
Ookim4的头像 - 宋马
评论 共1条

请登录后发表评论