thinkphp6解决vue跨域问题
在路由处加上allowCrossDomain()就可以了。跨域请求一般会发送一条OPTIONS的请求,一旦设置了跨域请求的话,不需要自己定义OPTIONS请求的路由,系统会自动加上。跨域请求系统会默认带上一些Header,包括:Access-Control-Allow-Origin:*Access-Control-Allow-Methods:GET, POST, PATCH, PUT, DELET
·
在路由处加上allowCrossDomain()就可以了。
跨域请求一般会发送一条OPTIONS的请求,一旦设置了跨域请求的话,不需要自己定义OPTIONS请求的路由,系统会自动加上。
跨域请求系统会默认带上一些Header,包括:
Access-Control-Allow-Origin:*
Access-Control-Allow-Methods:GET, POST, PATCH, PUT, DELETE
Access-Control-Allow-Headers:Authorization, Content-Type, If-Match, If-Modified-Since, If-None-Match, If-Unmodified-Since, X-Requested-With
第二种方法:在入口文件(index.php)加入防跨域代码:
header('Content-Type: text/html;charset=utf-8');
header('Access-Control-Allow-Origin:*');
header('Access-Control-Allow-Methods:POST,GET,OPTIONS,DELETE');
header('Access-Control-Allow-Credentials: true');
header('Access-Control-Allow-Headers: Content-Type,Content-Length,Accept-Encoding,X-Requested-with, Origin');
第三种方法:
在这里可以使用tp6的前置中间件
首先开启中间件的文件配置
然后创建一个中间件文件
最后配置
<?php
/**
* Created by PhpStorm.
* User: Administrator
* Date: 2021/4/9
* Time: 17:51
*/
declare (strict_types = 1);
namespace app\middleware;
use Closure;
use think\Config;
use think\Request;
use think\Response;
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);
}
}
原文链接:thinkphp6解决跨域 - 简书
更多推荐
已为社区贡献6条内容
所有评论(0)