我最近面临laravel 5.4这个错误,我会发送AJAX POST请求到自己的网站,并仍然得到同样的错误,我遇到这个错误是由于两个原因准确地说,
error: XMLHttpRequest cannot load https://[mydomain].com/quote/short. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://[mydomain].com' is therefore not allowed access.
原因上面的错误是,我张贴请求HTTP域从https域,所以当我把它变成https,错误就解决了,后来我又得到了相同的由于类似原因导致的错误,这是原因,这次该域名有www.
和要求的一个没有,我加了www.
后,它的工作就像一个魅力。
而对于跨源请求,我用以下溶液:
创建一个中间件(在我的情况CORS)具有代码下面
return $next($request)
->header('Access-Control-Allow-Origin', '*')
->header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
插入中间件成routeMiddleware阵列in kernal.php
'cors' => \App\Http\Middleware\Cors::class,
添加中间件的尊重路线
Route::get('myRoute', ['middleware' => 'cors' , 'uses'=> '[email protected]']
希望这个答案可以帮助别人面临着同样的问题,因为我自己。
简单,使用这个插件:https://github.com/barryvdh/laravel-cors – num8er
我这样做,那是我提到的中间件(忘了说)。我添加到内核中,看看我的要点 –
要如何保持它:''middleware'=> [\ Barryvdh \ Cors \ HandleCors :: class]' – num8er