美文网首页
thinkphp6解决 CORS 跨域

thinkphp6解决 CORS 跨域

作者: tangzhentian | 来源:发表于2021-10-21 14:30 被阅读0次

1,在app/middleware.php中添加

\think\middleware\AllowCrossDomain::class

中间件,这样就改成了

Access-Control-Allow-Origin: *

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

<?php
// +----------------------------------------------------------------------
// | Cookie设置
// +----------------------------------------------------------------------
return [
    // cookie 保存时间
    'expire'    => 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 跨域

      本文链接:https://www.haomeiwen.com/subject/levfaltx.html