Laravel 5 + AngularJS跨域CORS

Laravel 5 + AngularJS跨域CORS,第1张

Laravel 5 + AngularJS跨域CORS

我遇到了同样的问题,但是使用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/



欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/4974001.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-11-13
下一篇 2022-11-13

发表评论

登录后才能评论

评论列表(0条)

保存