laravel 跨域解決方案

我們?cè)谟?laravel 進(jìn)行開(kāi)發(fā)的時(shí)候,特別是前后端完全分離的時(shí)候,由于前端項(xiàng)目運(yùn)行在自己機(jī)器的指定端口(也可能是其他人的機(jī)器) , 例如 localhost:8000 , 而 laravel 程序又運(yùn)行在另一個(gè)端口,這樣就跨域了,而由于瀏覽器的同源策略,跨域請(qǐng)求是非法的。其實(shí)這個(gè)問(wèn)題很好解決,只需要添加一個(gè)中間件就可以了。

1.新建一個(gè)中間件

php?artisan?make:middleware?EnableCrossRequestMiddleware

2.書(shū)寫(xiě)中間件內(nèi)容

<?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-&gt;server('HTTP_ORIGIN')?:?''; ????????$allow_origin?=?[ ????????????'http://localhost:8000', ????????]; ????????if?(in_array($origin,?$allow_origin))?{ ????????????$response-&gt;header('Access-Control-Allow-Origin',?$origin); ????????????$response-&gt;header('Access-Control-Allow-Headers',?'Origin,?Content-Type,?Cookie,?X-CSRF-TOKEN,?Accept,?Authorization,?X-XSRF-TOKEN'); ????????????$response-&gt;header('Access-Control-Expose-Headers',?'Authorization,?authenticated'); ????????????$response-&gt;header('Access-Control-Allow-Methods',?'GET,?POST,?PATCH,?PUT,?OPTIONS'); ????????????$response-&gt;header('Access-Control-Allow-Credentials',?'true'); ????????} ????????return?$response; ????} }

$allow_origin 數(shù)組變量就是你允許跨域的列表了,可自行修改。

3.然后在內(nèi)核文件注冊(cè)該中間件

????protected?$middleware?=?[ ????????//?more ????????AppHttpMiddlewareEnableCrossRequestMiddleware::class, ????];

在 AppHttpKernel 類(lèi)的 $middleware 屬性添加,這里注冊(cè)的中間件屬于全局中間件。

然后你就會(huì)發(fā)現(xiàn)前端頁(yè)面已經(jīng)可以發(fā)送跨域請(qǐng)求了。

會(huì)多出一次 method 為 options 的請(qǐng)求是正常的,因?yàn)闉g覽器要先判斷該服務(wù)器是否允許該跨域請(qǐng)求。

更多Laravel相關(guān)技術(shù)文章,請(qǐng)?jiān)L問(wèn)Laravel框架入門(mén)教程欄目進(jìn)行學(xué)習(xí)!

以上就是

? 版權(quán)聲明
THE END
喜歡就支持一下吧
點(diǎn)贊9 分享