【问题标题】:Angular $http returns "no access control allow origin" header, but jQuery $.get request returns informationAngular $http 返回“no access control allow origin”标头,但 jQuery $.get 请求返回信息
【发布时间】:2014-09-04 18:52:38
【问题描述】:

jQuery $.get、$.post 怎么能得到想要的结果,但 Angular 却不能 $http.get、$http.post?为什么原始策略不适用于 Angular 而适用于 jquery?

Laravel 后端,角度前端。我正在考虑只使用 jQuery,因为它不会阻止客户端发生 CRUD 操作。

我配置了 $http 和 $httpProvider...

.run(function($http){
     $http.defaults.headers.common['Access-Control-Allow-Origin'] = "*";
     $http.defaults.headers.common['Access-Control-Allow-Methods'] = "GET, POST, PUT, DELETE, OPTIONS";
     $http.defaults.headers.common['Access-Control-Allow-Headers'] = "Authorization";
})
.config(function($httpProvider) {
    $httpProvider.defaults.useXDomain = true;
})

并且 laravel 正在发回适当的标头...

App::after(function($request, $response)
{
    // header('Access-Control-Allow-Origin', '*');
     $response->headers->set('Access-Control-Allow-Origin', '*');
});

所以奇怪的是 angular $http 无法从服务器获取任何内容并产生此错误:

XMLHttpRequest cannot load http://0.0.0.0:8000/api/test. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:9000' is therefore not allowed access. 

但是 jQuery $.get 和 $.post 可以正常工作!

$.post('http://0.0.0.0:8000/api/test', function(resp){
    console.log(resp);
});

我在这里做错了什么?

【问题讨论】:

  • +1 不知道为什么不赞成,这不是典型的 xDomain 问题
  • 你的 jQuery 是从 localhost:9000 (与 angular 相同的地方)运行还是在其他地方运行?
  • 您是否尝试过当前使用的其他浏览器?如果控制台上有更多错误信息,您也可以发布吗?

标签: angularjs laravel cors


【解决方案1】:
.config(['$httpProvider', function($httpProvider) {
        $httpProvider.defaults.useXDomain = true;
        delete $httpProvider.defaults.headers.common['X-Requested-With'];
    }
]);

仅将 useXDomain 设置为 true 是不够的。 AJAX 请求也与X-Requested-With 标头一起发送,这表明它们是 AJAX。删除标头是必要的,因此服务器不会拒绝传入的请求。

尝试在 filters.php 中添加这个:

App::before(function($request)
{
    if (Request::getMethod() == "OPTIONS") {
        $headers = array(
        'Access-Control-Allow-Methods'=> 'POST, GET, OPTIONS, PUT, DELETE',
        'Access-Control-Allow-Headers'=> 'X-Requested-With, content-type, Authorization',);
        return Response::make('', 200, $headers);
    }
});

飞行前请求可能失败

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2018-04-16
  • 2013-07-08
  • 2019-03-18
  • 1970-01-01
  • 2016-08-21
  • 1970-01-01
相关资源
最近更新 更多