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

时间:2015-10-16 17:13:33

标签: laravel laravel-5 cors

我正在使用Laravel 5和一个名为CORS的库。我正面临一个错误,我不明白它是什么以及它为什么会发生。

我正在开发一个将由网站的前端和应用程序使用的API。

我正在尝试对API进行ajax调用:

$.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)}
});

然而我得到了这个错误:

  

XMLHttpRequest无法加载http://myapi.com/call。回应   预检具有无效的HTTP状态代码500

但是,当我从请求中删除以下行时工作正常。

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

编辑:我的config / cors.php

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

关于如何解决它的任何想法?

2 个答案:

答案 0 :(得分:3)

以下修复对我有用(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');
}

并且对于获得预检请求的每条路线,也要添加选项方法

Route::post('/yourroute', 'YourController@index');
Route::options('/yourroute', 'YourController@index');

答案 1 :(得分: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