2015-10-16 83 views
1

我正在使用Laravel 5和一個名爲CORS的庫。我面臨着一個錯誤,我並不真正瞭解它是什麼以及它發生的原因。Laravel 5 CORS - XMLHttpRequest無法加載http://myapi.com。預檢的響應具有無效的HTTP狀態代碼500

我正在開發一個將由網站的前端和應用程序使用的API。

我試圖做一個AJAX調用API:

$.ajax({ 
    url: 'http://myapi.com/call', 
    type: 'GET', 
    headers: {'Authorization' : 'Bearer token123'}, 
    crossDomain: true, 
    contentType: 'application/x-www-form-urlencoded; charset=UTF-8', 
    success : function(data) { console.log(data);}, 
    error: function(xhr) {console.log(xhr)} 
}); 

但是我得到這個errro:

的XMLHttpRequest無法加載http://myapi.com/call。 預檢的無效HTTP狀態代碼500

但是,當我從請求中刪除以下行時正常工作。

headers: {'Authorization' : 'Bearer token123'}, 

編輯:我的配置/ cors.php

'supportsCredentials' => false, 
'allowedOrigins' => ['*'], 
'allowedHeaders' => ['*'], 
'allowedMethods' => ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'], 
'exposedHeaders' => [], 
'maxAge' => 0, 
'hosts' => [], 

有關如何解決它的任何想法?

+2

當您的服務器發送200時,您的服務器正在發送500個響應。您能否顯示負責CORS處理的相關服務器端? CORS預檢請求是在「非簡單」請求之前完成的OPTIONS請求,包括具有罕見標題的請求。如果您對CORS一無所知,請參閱http://www.html5rocks.com/en/tutorials/cors/ – apsillers

回答

2

你在laravel服務器配置CORS,有幾個選項做同樣的

# one of the way is to add below in .htaccess (modify accordingly) 

Header add Access-Control-Allow-Origin "*" 
Header add Access-Control-Allow-Headers "origin, x-requested-with, content-type" 
Header add Access-Control-Allow-Methods "PUT, GET, POST, DELETE, OPTIONS" 

# other options you can refer to below link of laracasts 

來源:https://laracasts.com/discuss/channels/requests/laravel-5-cors-headers-with-filters/?page=2

+0

我編輯了該文章並張貼了CORS的配置選項。你可以看一下嗎? – andrepibo

+0

narendra,我試過你在.htaccess上的代碼修改,並且收到以下消息: XMLHttpRequest無法加載http://myapi.com/call。對預檢請求的響應不會通過訪問控制檢查:請求的資源上不存在「訪問控制 - 允許來源」標頭。因此不允許原產地'null'訪問。響應的HTTP狀態碼爲500. 有什麼建議嗎? – andrepibo

2

下面的修復工作對我來說(Laravel 5.4) 您可以添加以下爲laravel CORS中間件

public function handle($request, Closure $next) 
{ 
    if ($request->getMethod() == "OPTIONS") { 
     return response(['OK'], 200)->withHeaders([ 
      'Access-Control-Allow-Origin' => '*', 
      'Access-Control-Allow-Methods' => 'GET, POST, PUT, DELETE', 
      'Access-Control-Allow-Credentials' => true, 
      'Access-Control-Allow-Headers' => 'Authorization, Content-Type', 
     ]); 
    } 

    return $next($request) 
    ->header('Access-Control-Allow-Origin', '*') 
    ->header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE') 
    ->header('Access-Control-Allow-Credentials', true) 
    ->header('Access-Control-Allow-Headers', 'Authorization,Content-Type'); 
} 

,併爲每個路線的它得到預檢要求增加一個選擇了我thod too

Route::post('/yourroute', '[email protected]'); 
Route::options('/yourroute', '[email protected]'); 
相關問題