thinkphp6解决 CORS 跨域

1,在app/middleware.php中添加

\think\middleware\AllowCrossDomain::class

中间件,这样就改成了

Access-Control-Allow-Origin: *

*是不安全的,可以在config/cookie.php配置cookie 有效域名的domain

 0,
    // cookie 保存路径
    'path'      => '/',
    // cookie 有效域名
    'domain'    => '您的域名',
    //  cookie 启用安全传输
    'secure'    => false,
    // httponly设置
    'httponly'  => false,
    // 是否使用 setcookie
    'setcookie' => true,
];

如果接口请求发送了token,会提示Access-Control-Allow-Headers这个问题,tp6默认是这样

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',
    ];

可以在'Access-Control-Allow-Headers' 这一样加上XXX-token,

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'     => 'xxx-token,Authorization, Content-Type, If-Match, If-Modified-Since, If-None-Match, If-Unmodified-Since, X-CSRF-TOKEN, X-Requested-With',
    ];

我在搞这个时还遇见post请求变成get


image.png

把method改成了type

你可能感兴趣的:(thinkphp6解决 CORS 跨域)