Laravel 5 CORS - XMLHttpRequest cannot load http:/

2019-02-19 19:00发布

I am using Laravel 5 and a library called CORS. I am facing an error that I don't really understand what it is and why it is happening.

I am developing an API that is gonna be used by a website's front-end and an app.

I am trying to do an ajax call to the 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)}
});

However I got this errro:

XMLHttpRequest cannot load http://myapi.com/call. Response for preflight has invalid HTTP status code 500

However, when I remove the following line from the request works fine.

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

EDIT: my config/cors.php

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

Any idea about how to solve it?

2条回答
三岁会撩人
2楼-- · 2019-02-19 19:35

The following fix worked for me (Laravel 5.4) You can add the following to the laravel cors middleware

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');
}

and for each of your routes which gets preflight requests add a options method too

Route::post('/yourroute', 'YourController@index');
Route::options('/yourroute', 'YourController@index');
查看更多
我只想做你的唯一
3楼-- · 2019-02-19 19:47

Did you configure CORS on server in laravel, there are couple of option to do the same

# 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

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

查看更多
登录 后发表回答