Laravel框架的前后端分离的跨域CORS问题处理

  •   
  • 2147
  • PHP
  • 0
  • super_dodo
  • 2020/10/15

最近处理的一个项目是laravel+vue的项目,原先的时候是吧前端项目放在后端代码的public目录下面,放在同一个目录下面的话是不会存在跨域相关的问题。

现在根据产品的需要和规划,要把前端项目打包后独立出来

API接口后端的独立域名
https://api.dodobook.net

前端Web端的域名独立如下
https://web.dodobook.net

现在需要在前端不项目去跨域请求API接口

直接访问的时候会出现大量的CORS相关的跨域报错例如
Access to XMLHttpRequest at 'http://www.dodobook.me/comm/test-ajax?hello=dodo' from origin 'http://www.dodobook.cc' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

试了好几种方式,改nginx,改代码等方式都未果,也可能是自己某些方面疏忽踩坑。

现在贴出来现在的处理方式.使用中间件。

新建一个中间件
php artisan make:middleware EnableCrossRequestMiddleware

书写中间件内容


namespace App\Http\Middleware;
use Closure;

class EnableCrossRequestMiddleware
{
/**
* Handle an incoming request.
*
* @param  \Illuminate\Http\Request  $request
* @param  \Closure  $next
* @return mixed
/
public function handle($request, Closure $next)
{
$origin = $request->server('HTTP_ORIGIN') ? $request->server('HTTP_ORIGIN') : '';
$allow_origin = [
'https://web.dodobook.net',
'https://web.abcd.com',
];
if (in_array($origin, $allow_origin)) {
//    $response->header('Access-Control-Allow-Origin', '</em>');
header("Access-Control-Allow-Origin:{$origin}");  //https 不可以用*号通配符
header('Access-Control-Allow-Headers:Origin,Content-Type,Cookie,X-CSRF-TOKEN,Accept,Authorization,X-XSRF-TOKEN,lang,sign,dodo');
header('Access-Control-Expose-Headers:Authorization,authenticated');
header('Access-Control-Allow-Methods:GET,POST,PUT,OPTIONS,PATCH,DELETE,HEAD');
header('Access-Control-Allow-Credentials:true');
}
$response = $next($request);    //这个是进程--在请求之前就加上
return $response;
}
}
<h1>然后在内核文件注册该中间件</h1>
protected $middleware = [
// more
App\Http\Middleware\EnableCrossRequestMiddleware::class,
];
在 App\Http\Kernel 类的 $middleware 属性添加,这里注册的中间件属于全局中间件。

然后你就会发现前端页面已经可以发送跨域请求了。

会多出一次 method 为 options 的请求是正常的,因为浏览器要先判断该服务器是否允许该跨域请求。

参考文章:https://learnku.com/articles/6504/laravel-cross-domain-solution