栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

Laravel 5 + AngularJS跨域CORS

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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/



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/391054.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号