前言
众所周知我们大家在用 laravel 进行开发的时候,特别是前后端完全分离的时候,由于前端项目运行在自己机器的指定端口(也可能是其他人的机器) , 例如 localhost:8000 , 而 laravel 程序又运行在另一个端口,这样就跨域了,而由于浏览器的同源策略,跨域请求是非法的。其实这个问题很好解决,只需要添加一个中间件就可以了。下面话不多说了,来随着小编一起看看详细的解决方案吧。
解决方案:
1、新建一个中间件
php artisan make:middleware enablecrossrequestmiddleware
2、书写中间件内容
<?php
namespace apphttpmiddleware;
use closure;
class enablecrossrequestmiddleware
{
/**
* handle an incoming request.
*
* @param illuminatehttprequest $request
* @param closure $next
* @return mixed
*/
public function handle($request, closure $next)
{
$response = $next($request);
$origin = $request->server('http_origin') ? $request->server('http_origin') : '';
$allow_origin = [
'http://localhost:8000',
];
if (in_array($origin, $allow_origin)) {
$response->header('access-control-allow-origin', $origin);
$response->header('access-control-allow-headers', 'origin, content-type, cookie, x-csrf-token, accept, authorization, x-xsrf-token');
$response->header('access-control-expose-headers', 'authorization, authenticated');
$response->header('access-control-allow-methods', 'get, post, patch, put, options');
$response->header('access-control-allow-credentials', 'true');
}
return $response;
}
}
$allow_origin 数组变量就是你允许跨域的列表了,可自行修改。
3、然后在内核文件注册该中间件
protected $middleware = [
// more
apphttpmiddlewareenablecrossrequestmiddleware::class,
];
在 apphttpkernel 类的 $middleware 属性添加,这里注册的中间件属于全局中间件。
然后你就会发现前端页面已经可以发送跨域请求了。
会多出一次 method 为 options 的请求是正常的,因为浏览器要先判断该服务器是否允许该跨域请求。
总结
以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,如果有疑问大家可以留言交流,谢谢大家对硕编程的支持。
【说明】:本文章由站长整理发布,文章内容不代表本站观点,如文中有侵权行为,请与本站客服联系(QQ:254677821)!