2017-12-26 10 views
0

Swagger UI経由で作成されたAPIを起動する際にCORSエラーが発生しました。だから私は、このCORSの問題解決するミドルウェア作成:Swagger UIを使用してテスト中にApiでCORSエラーを解決する方法(ルーメンを使用して実装)

<?php 

namespace App\Http\Middleware; 

use Closure; 

class CorsMiddleware 
{ 
    /** 
    * Handle an incoming request. 
    * 
    * @param \Illuminate\Http\Request $request 
    * @param \Closure $next 
     * @return mixed 
    */ 
    public function handle($request, Closure $next) 
    { 
     $headers = [ 
      'Access-Control-Allow-Origin'  => '*', 
      'Access-Control-Allow-Methods'  => 'POST, GET, OPTIONS, PUT, DELETE', 
      'Access-Control-Allow-Credentials' => 'true', 
      'Access-Control-Max-Age'   => '86400', 
      'Access-Control-Allow-Headers'  => 'Content-Type, Authorization, X-Requested-With' 
     ]; 

     if ($request->isMethod('OPTIONS')) 
     { 
      return response()->json('{"method":"OPTIONS"}', 200, $headers); 
     } 

     $response = $next($request); 
     foreach($headers as $key => $value) 
     { 
      $response->header($key, $value); 
     } 

     return $response; 
    } 
} 

をそして今、これを使用した後に、私のコルスエラーの問題が解決したが、APIがために、エラーを投げ、正しく動作していない、そのAPIのための私のルートでこのミドルウェアを使用しましたコードの下:私はルートからミドルウェアを削除すると

//**** code that throwing error starts **** 

     $config = app()->make('config'); 

      $data = array_merge([ 
      'client_id'  => $config->get('secrets.client_id'), 
      'client_secret' => $config->get('secrets.client_secret'), 
      'grant_type' => $grantType, 
      'username' =>$data['username'], 
      'password' =>$data['password'] 
     ], $data); 

      $http = new Client(); 

      $headers = ['Content-Type' => 'application/json']; 
      $guzzleResponse = $http->post($config->get('app.url').'/oauth/token', [ 

      'form_params' => $data, 
     ]); 
      $tokenDetails = json_decode($guzzleResponse->getBody(),true); 

//************** Code throwing error ends ****** 

は今APIはPOSTMANと正常に動作しているが、闊歩ためCORSエラーを投げ、私はCORSの問題を解決するためのミドルウェアを使用した場合、APIは正常に動作していません。

+0

エラーは何ですか? –

+0

ミドルウェアを使用しない場合はCORSエラー、使用する場合は500内部サーバーエラー。 –

答えて

0

の.htaccess

するRewriteCondの%{REQUEST_METHOD} OPTIONS のRewriteRule ^この行を追加し(。*)$ $ 1 [R = 200、L] をRewriteEngine後行で

関連する問題