2016-12-06 32 views
1

我創建了處理我的CORS請求中間件:CORS middlware上預檢OPTIONS請求運行,但不能在主請求

<?php 

namespace App\Http\Middleware; 

use Closure; 

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

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

而且我已經把它添加到我的kernel.php

'api' => [ 
     'throttle:60,1', 
     'bindings', 
     'cors' 
    ], 

當我向/user發送GET請求時,一切正常,但是當我向/api/answers發出POST請求時,出現CORS錯誤:XMLHttpRequest cannot load http://localhost:8000/api/answers. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8080' is therefore not allowed access.。兩者都是在我api.php

<?php 

use Illuminate\Http\Request; 

/* 
|-------------------------------------------------------------------------- 
| API Routes 
|-------------------------------------------------------------------------- 
| 
| Here is where you can register API routes for your application. These 
| routes are loaded by the RouteServiceProvider within a group which 
| is assigned the "api" middleware group. Enjoy building your API! 
| 
*/ 
Route::group(['middleware' => ['auth:api']], function() { 
    Route::get('/user', function (Request $request) { 
     $user = $request->user(); 
     $user->load('locations.company'); 
     $user->load([ 
      'questionlists' => function ($query) { 
       $query->with('questions.type'); 
       $query->with('difficulty'); 
      } 
     ]); 

     $amountOfCompletes = count($user->completes); 
     $user->amountOfCompletes = $amountOfCompletes; 
     return $user; 
    }); 

    Route::resource('answers', 'AnswersController'); 
}); 
+0

我建議使用此https://github.com/barryvdh/laravel- CORS。爲此節省一些時間。 – ssuhat

+0

我試過了,給了我一個不同的問題:http://stackoverflow.com/questions/40978486/barryvdh-laravel-cors-not-working-for-my-routes?noredirect=1#comment69172987_40978486 – g3mini

回答

0

使用類引用,如果您還沒有定義中間件作爲路線中間件

'api' => [ 
     'throttle:60,1', 
     'bindings', 
     App\Http\Middleware\Cors::class 
    ], 
+0

我的道歉,我有: ''cors'=> \ App \ Http \ Middleware \ Cors :: class,'我試着將它添加到帖子中,但是我的光標在SO的編輯器 – g3mini

+0

中不斷跳躍,您可以通過將dd添加到中間件來檢查並確認是否調用了中間件或繞過?我也會建議使用laravel-cors包 https://github.com/barryvdh/laravel-cors –

+0

那個包不適合我,不幸的是,dd沒有做任何事情 – g3mini

相關問題