溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點(diǎn)擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

laravel開發(fā)中跨域怎么辦

發(fā)布時間:2021-07-16 11:22:52 來源:億速云 閱讀:135 作者:小新 欄目:開發(fā)技術(shù)

小編給大家分享一下laravel開發(fā)中跨域怎么辦,相信大部分人都還不怎么了解,因此分享這篇文章給大家參考一下,希望大家閱讀完這篇文章后大有收獲,下面讓我們一起去了解一下吧!

解決方案:

1、新建一個中間件

php artisan make:middleware EnableCrossRequestMiddleware

2、書寫中間件內(nèi)容

<?php
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)
 {
 $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 數(shù)組變量就是你允許跨域的列表了,可自行修改。

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

 protected $middleware = [
 // more
 App\Http\Middleware\EnableCrossRequestMiddleware::class,
 ];

在 App\Http\Kernel 類的 $middleware 屬性添加,這里注冊的中間件屬于全局中間件。
然后你就會發(fā)現(xiàn)前端頁面已經(jīng)可以發(fā)送跨域請求了。

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

以上是“l(fā)aravel開發(fā)中跨域怎么辦”這篇文章的所有內(nèi)容,感謝各位的閱讀!相信大家都有了一定的了解,希望分享的內(nèi)容對大家有所幫助,如果還想學(xué)習(xí)更多知識,歡迎關(guān)注億速云行業(yè)資訊頻道!

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI