TP 框架提供的内置类: \think\middleware\AllowCrossDomain::class
开启跨域
// 全局中间件定义文件
return [
// 全局请求缓存
// \think\middleware\CheckRequestCache::class,
// 多语言加载
// \think\middleware\LoadLangPack::class,
// Session初始化
\think\middleware\SessionInit::class,
// 全局注册 middleware token
// app\middleware\CheckToken::class
// 跨域请求
\think\middleware\AllowCrossDomain::class
];
今天,在用ThinkPHP8做前后端分离配置跨域时,发现了一个小小的问题,就是我这块儿微信小程序发送token是完全正常的,但是使用web端网页发送请求它就会出现下面的错误
Access to XMLHttpRequest at 'http://robin.com/Article?pagesize=10&page=1&status=-1&author=&title=' from origin 'http://localhost:5173' has been blocked by CORS policy: Request header field token is not allowed by Access-Control-Allow-Headers in preflight response.
因为我使用的是TP框架自带的跨域配置类 \think\middleware\AllowCrossDomain::class,然后去查看了一下它的源码,发现其中确实少掉了Origin token的支持
源码如下:
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006~2023 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st
// +----------------------------------------------------------------------
declare(strict_types=1);
namespace think\middleware;
use Closure;
use think\Config;
use think\Request;
use think\Response;
/**
* 跨域请求支持
*/
class AllowCrossDomain
{
protected $cookieDomain;
protected $header = [
'Access-Control-Allow-Credentials' => 'true',
'Access-Control-Max-Age' => 1800,
'Access-Control-Allow-Methods' => 'GET, POST, PATCH, PUT, DELETE, OPTIONS',
// 此处就是 token 不支持设置的原因,因为配置项少了
'Access-Control-Allow-Headers' => 'Authorization, Content-Type, If-Match, If-Modified-Since, If-None-Match, If-Unmodified-Since, X-CSRF-TOKEN, X-Requested-With',
];
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 $request, Closure $next, array $header = []): Response
{
$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 || str_contains($origin, $this->cookieDomain))) {
$header['Access-Control-Allow-Origin'] = $origin;
} else {
$header['Access-Control-Allow-Origin'] = '*';
}
}
return $next($request)->header($header);
}
}
只需要将上面的请求头配置修改如下即可(添加上 Origin, token ):
'Access-Control-Allow-Headers' => 'Authorization, Content-Type, If-Match, If-Modified-Since, If-None-Match, If-Unmodified-Since, X-CSRF-TOKEN, X-Requested-With,Origin, token',
CORS(跨源资源共享)是一种更为现代和推荐的跨域解决方案。它通过服务器端设置响应头信息,允许来自不同源的客户端进行跨域请求。
wx.request({
url: 'http://example.com/api', // 指定请求的URL地址
method: 'GET', // 指定请求方式
header: {
'Content-Type': 'application/json', // 设置请求头信息
'Access-Control-Allow-Origin': '*' // 设置允许跨域的源地址
},
success: function(res) {
// 请求成功后的回调函数
console.log(res.data)
},
fail: function(res) {
// 请求失败后的回调函数
console.log(res)
}
})
Access-Control-Allow-Origin: *
Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS
Access-Control-Allow-Headers: Origin, Content-Type, X-Requested-With, token
// request 拦截器
// 可以自请求发送前对请求做一些处理
// 比如统一加token,对请求参数统一加密
request.interceptors.request.use(config => {
config.headers['Content-Type'] = 'application/json;charset=utf-8';
let token = localStorage.getItem("token") ? JSON.parse(localStorage.getItem("token")) : ""
if(token!=""){
config.headers['token'] = token; // 设置请求头
}
return config
}, error => {
return Promise.reject(error)
});