我遇到了同样的问题,但是使用jQuery并花了我数周的时间才能得到一个好的解决方案。
创建一个Cors中间件:App Http Middleware Cors.php
namespace AppHttpMiddleware;use Closure;class Cors{ public function handle($request, Closure $next) { return $next($request) ->header('Access-Control-Allow-Origin', $_SERVER['HTTP_ORIGIN']) // Depending of your application you can't use '*' // Some security CORS concerns //->header('Access-Control-Allow-Origin', '*') ->header('Access-Control-Allow-Methods', 'POST, OPTIONS') ->header('Access-Control-Allow-Credentials', 'true') ->header('Access-Control-Max-Age', '10000') ->header('Access-Control-Allow-Headers', 'Content-Type, Authorization, X-Requested-With'); }}
记得在App Http Kernel中设置Cors别名
protected $routeMiddleware = [ ... 'cors' => AppHttpMiddlewareCors::class,];
在Routes内部,您可以将中间件与group一起使用或直接定向到特定的路由,例如:
Route::match(['post', 'options'], 'api/...', 'ApiXController@method')->middleware('cors');
如果有人对jQuery有此问题,我建议使用$ .ajax,而不是$
.get,$。post。当您使用此方法时,jQuery使用XMLHttpRequest发送数据并将content-type设置为application /
x-www-form-urlenpred,无法更改它,因此请使用Ajax。
例如:
$.ajax({ type: 'POST', url: 'www.foo.bar/api', contentType: "application/json", xhrFields: { // The 'xhrFields' property sets additional fields on the XMLHttpRequest. // This can be used to set the 'withCredentials' property. // Set the value to 'true' if you'd like to pass cookies to the server. // If this is enabled, your server must respond with the header // 'Access-Control-Allow-Credentials: true'. withCredentials: true }, headers: { // Set any custom headers here. // If you set any non-simple headers, your server must include these // headers in the 'Access-Control-Allow-Headers' response header. 'Accept': 'application/json' }, data: '{"some":"json data"}', success: function (data) { console.log('AJAX version'); console.log("Works!") }, });
切记:如果在请求标头上使用application / json,则必须提供“ OPTIONS”方法来进行预检。
有关CORS的更多信息:http
://www.html5rocks.com/en/tutorials/cors/
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)