Laravel 5 CORS - XMLHttpRequest无法加载http://myapi.com。预检的响应具有无效的HTTP状态代码500

问题描述:

我正在使用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

你在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

下面的修复工作对我来说(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]');