2015-11-06 119 views
7

我一直在試圖解決這個問題一段時間,但無法破解它。Laravel CORS中間件無法發佈帖子和資源請求

我有一個Laravel後端和角前端。由於前端需要成爲網絡和移動科爾多瓦應用程序,因此它們位於不同的域中。

即使加入CORS中間件,郵政和資源請求後會加載失敗,我在控制檯中看到一個

No 'Access-Control-Allow-Origin' header is present on the requested resource 

錯誤。

下面的GET請求沒有很好地工作: -

Route::get('example', ['middleware' => 'cors', function(){ 
    return Response::json(array('name' => 'Steve Jobs 1', 'company' => 'Apple')); 
}]); 

但其後的失敗 -

Route::group(['middleware' => 'cors'], function() { 
Route::group(['prefix' => 'api'], function() 
{ 
    Route::resources('authenticate', 'AuthenticateController', ['only' => ['index']]); 
    Route::post('authenticate', '[email protected]'); 
}); 
}); 

我下面https://scotch.io/tutorials/token-based-authentication-for-angularjs-and-laravel-apps

我CORS.php

class CORS 
{ 
/** 
* Handle an incoming request. 
* 
* @param \Illuminate\Http\Request $request 
* @param \Closure $next 
* @return mixed 
*/ 
public function handle($request, Closure $next) 
{ 
    header("Access-Control-Allow-Origin: *"); 

    // ALLOW OPTIONS METHOD 
    $headers = [ 
     'Access-Control-Allow-Methods'=> 'POST, GET, OPTIONS, PUT, DELETE', 
     'Access-Control-Allow-Headers'=> 'Content-Type, X-Auth-Token, Origin' 
    ]; 
    if($request->getMethod() == "OPTIONS") { 
     // The client-side application can set only headers allowed in Access-Control-Allow-Headers 
     return Response::make('OK', 200, $headers); 
    } 

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

kernal.php

class Kernel extends HttpKernel 
{ 

protected $middleware = [ 
    \Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class, 
    \App\Http\Middleware\EncryptCookies::class, 
    \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class, 
    \Illuminate\Session\Middleware\StartSession::class, 
    \Illuminate\View\Middleware\ShareErrorsFromSession::class, 
    /*\App\Http\Middleware\VerifyCsrfToken::class,*/ 
]; 


protected $routeMiddleware = [ 
    'auth' => \App\Http\Middleware\Authenticate::class, 
    'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class, 
    'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class, 
    'jwt.auth' => \Tymon\JWTAuth\Middleware\GetUserFromToken::class, 
    'jwt.refresh' => \Tymon\JWTAuth\Middleware\RefreshToken::class, 
    'cors' => 'App\Http\Middleware\CORS', 
]; 
} 
+0

你可以發佈你的請求返回的HTTP響應代碼嗎?我最近遇到類似的問題,我的迴應是返回一個500的代碼,一個內部服務器錯誤。原來,這與我的標題無關,但事實是我沒有正確地做CSRF。禁用CSRF使其工作。也許嘗試一下,看看它是否真的是一個CORS問題或其他類似於我的情況? –

+0

好吧,我看到你禁用CSRF的地方,所以不是這樣。但是,瞭解HTTP響應代碼可以提供一些見解。 –

回答

0

Seems it has something to do with post request headers after the token is granted to a user. jwt adds in an authorization header and a cookie 好像它是與POST請求頭令牌被授予用戶後。

我在我的控制器中的CORS中間件添加構建像這樣:在

 public function __construct() 
    { 
     // Apply the jwt.auth middleware to all methods in this controller 
     // except for the index method. 
     $this->middleware('jwt.auth', ['except' => ['index']]); 
     $this->middleware('cors'); 

    } 

智威湯遜在授權頭和餅乾

0

也許你可以使用下面圍繞它暫時得到增加我的內核:

protected $routeMiddleware = [ 
    'auth' => \App\Http\Middleware\Authenticate::class, 
    'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class, 
    'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class, 

    'jwt.auth' => \Tymon\JWTAuth\Middleware\GetUserFromToken::class, 
    'jwt.refresh' => \Tymon\JWTAuth\Middleware\RefreshToken::class, 
    'cors'=> \Barryvdh\Cors\HandleCors::class 


]; 

這似乎是爲我工作。另外,請檢查您的laravel日誌並調試您的控制器。我的控制器中有一個輸入錯誤,客戶端控制檯中的http響應是cors錯誤。

+0

不,這不適用於我 –

+0

你檢查過你的存儲/日誌/ laravel.log嗎?因爲如果控制器中有任何語法錯誤,客戶端消息仍然會顯示:(index):1 XMLHttpRequest無法加載http:// localhost:8000/api/v1/partner。請求的資源上沒有「Access-Control-Allow-Origin」標題。原因'http:// localhost:9001'因此不被允許訪問。該響應具有HTTP狀態碼500。 –

0

現在幾個小時有同樣的問題。嘗試了不同的解決方案(使用barryvdh/laravel-cors library,製作了我自己的CORS中間件,在index.php文件中添加了頭文件),但沒有任何幫助。

現在我正在使用https://github.com/neomerx/cors-illuminate,它的工作原理。

cors-illuminate庫和laravel-cors庫之間的區別之一是安裝指南。 在CORS照亮引導它明確地說,你有後直接

\Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class, 

也許laravel-CORS圖書館也將努力增加中間件線,如果直接在CheckForMaintenanceMode中間件之後添加的中間件。沒有嘗試過。

0

在我的情況下,錯誤是我執行調用之前使用jwt進行認證的請求。 我有這個代碼,導致此問題:

function store(Request $request) 
{ 
    $producto = new Producto($request->json()->all()); 
    $this->currentUser = JWTAuth::parseToken()->authenticate(); 
    $producto->cliente_id = $this->currentUser->cliente_id; 
    $producto->save(); 
    return json_encode($producto); 
} 

正如你所看到的,JWTAuth線是它使用$請求前行。 您可以在JWTAuth線移動到抗凍線功能或類似這樣的類中創建一個構造函數:

function __construct() { 
    $this->currentUser = JWTAuth::parseToken()->authenticate(); 
} 

和解決的問題CORS。 我使用Barryvdh Cors。