业务需要如果是完全的前后端分离,需要前端跨域请求后端接口的话,就可添加跨域中间件,而无需在PHP文件中设置可跨域。

并且,跨域中间件可只设置一个域名的跨域请求,也可通过配置文件添加多个域名的跨域请求。

首先,在app\Http\Middleware下新建Cors.php

 1 <?php
 2 
 3 namespace App\Http\Middleware;
 4 
 5 use Closure;
 6 
 7 class Cors
 8 {
 9     /**
10      * Handle an incoming request.
11      *
12      * @param  \Illuminate\Http\Request  $request
13      * @param  \Closure  $next
14      * @return mixed
15      */
16     public function handle($request, Closure $next)
17     {
18         $response = $next($request);
19         $response->header('Access-Control-Allow-Origin', 'http://localhost:8080');
20         $response->header('Access-Control-Allow-Headers', 'Origin, Content-Type, Cookie, Accept, multipart/form-data, application/json');
21         $response->header('Access-Control-Allow-Methods', 'GET, POST, PATCH, PUT, OPTIONS');
22         $response->header('Access-Control-Allow-Credentials', 'true');
23         return $response;
24     }
25 }

然后在app\Http\Kernel.php(启动函数) 中加入 $middleware数组下加入 

1 \App\Http\Middleware\Cors::class

如图:

 

posted on 2017-12-13 17:54  彼岸无花  阅读(238)  评论(0)    收藏  举报