亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

Laravel 6 CORS 政策問題與 API

Laravel 6 CORS 政策問題與 API

PHP
慕桂英546537 2022-06-11 10:11:16
這是我嘗試過的中間件 return $next($request)        ->header('Access-Control-Allow-Origin', '*')        ->header('Access-Control-Allow-Credentials', 'true')        ->header('Access-Control-Allow-Headers', 'Origin, Content-Type, Authorization, X-Requested-With, Accept, X-Token-Auth, Application')        ->header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');API 路由Route::group(['middleware' => ['cors', 'auth:api']], function() {Route::options('{any}');Route::post('user/profile','UserController@profile');內核.phpprotected $routeMiddleware = [    'cors' => \App\Http\Middleware\Cors::class,但是,我仍然在來自另一個來源的 API 調用中收到此錯誤。對預檢請求的響應未通過訪問控制檢查:請求的資源上不存在“Access-Control-Allow-Origin”標頭。任何原因?
查看完整描述

2 回答

?
炎炎設計

TA貢獻1808條經驗 獲得超4個贊

最簡單的解決方案 轉到 bootstrap 文件夾并打開 app.php 文件。然后只需在文件頂部添加這些行。應用程序.php


  header('Access-Control-Allow-Origin: *');

  header('Access-Control-Allow-Methods: *');

  header('Access-Control-Allow-Headers: *');

另一個解決方案:


      php artisan make:middleware Cors

現在從 App\Http\Middleware 文件夾中打開 Cors.php 并用以下代碼替換 handle() 函數:


Cors.php


  public function handle($request, Closure $next)

  {

      return $next($request)

          ->header('Access-Control-Allow-Origin', '*')

          ->header('Access-Control-Allow-Methods', 'GET, POST, PUT, PATCH, DELETE,


        OPTIONS')

          ->header('Access-Control-Allow-Headers', 'Content-Type, Authorizations');

  }

最后,從 App\Http 文件夾中打開 Kernel.php,將以下行添加到 $middleware 數組中:


  protected $middleware = [

      ...

      \App\Http\Middleware\Cors::class,

  ];

現在運行應用程序并從任何地方調用 API。


查看完整回答
反對 回復 2022-06-11
?
人到中年有點甜

TA貢獻1895條經驗 獲得超7個贊

需要 composer.json 中的fruitcake/laravel-cors 包并更新您的依賴項:


composer require fruitcake/laravel-cors

全球使用


要允許所有路由使用 CORS,請在app/Http/Kernel.php類的 $middleware 屬性中添加 HandleCors 中間件:


protected $middleware = [

    // ...

    \Fruitcake\Cors\HandleCors::class,

];

配置


php artisan vendor:publish --tag="cors"

現在更新配置以定義要在其上運行 CORS 服務的路徑(請參閱下面的配置):


配置/cors.php


'paths' => ['api/*'],

更多細節https://github.com/fruitcake/laravel-cors


查看完整回答
反對 回復 2022-06-11
  • 2 回答
  • 0 關注
  • 185 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號