您好,欢迎访问一九零五行业门户网

laravel 跨域解决方案

我们在用 laravel 进行开发的时候,特别是前后端完全分离的时候,由于前端项目运行在自己机器的指定端口(也可能是其他人的机器) , 例如 localhost:8000 , 而 laravel 程序又运行在另一个端口,这样就跨域了,而由于浏览器的同源策略,跨域请求是非法的。其实这个问题很好解决,只需要添加一个中间件就可以了。
1.新建一个中间件
php artisan make:middleware enablecrossrequestmiddleware
2.书写中间件内容
<?phpnamespace 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) { $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 app\http\middleware\enablecrossrequestmiddleware::class, ];
在 app\http\kernel 类的 $middleware 属性添加,这里注册的中间件属于全局中间件。
然后你就会发现前端页面已经可以发送跨域请求了。
会多出一次 method 为 options 的请求是正常的,因为浏览器要先判断该服务器是否允许该跨域请求。
更多laravel相关技术文章,请访问laravel框架入门教程栏目进行学习!
以上就是laravel 跨域解决方案的详细内容。
其它类似信息

推荐信息