【问题标题】:CORS error with AngularJS post only in FireFoxAngularJS 的 CORS 错误仅在 FireFox 中发布
【发布时间】:2015-11-01 16:31:03
【问题描述】:

在 Ionic 应用程序中发出跨源请求时,我只遇到了 FireFox 的问题(因此它使用的是 AngularJS)。 js 应用程序正在对 Laravel 5.1 API 执行 $http.post(),我仅在 FireFox (39.0.3) 中收到以下错误:

跨域请求被阻止:同源策略不允许读取位于http://blah.dev/endpoint 的远程资源。 (原因:CORS 预检通道的 CORS 标头“Access-Control-Allow-Headers”中缺少令牌“content-type”)。

这是在我的本地主机上(OSX Mavericks)。并且在 Chrome 和 Safari 中运行良好,只有 FireFox 出现错误。我已清除缓存,并在“私人窗口”中尝试,结果相同。

这是为处理 OPTIONS 请求而定义的 Laravel 路由:

Route::options('endpoint', function() {
    return response('OK')
        ->header('Access-Control-Allow-Headers ', 'Origin, Authorization, X-Requested-With, Content-Type, Accept')
        ->header('Access-Control-Allow-Methods', 'POST, GET, OPTIONS')
        ->header('Access-Control-Allow-Origin', '*')
        ->header('Cache-Control', 'no-store, no-cache, must-revalidate, post-check=0, pre-check=0')
        ;
});

Route::post('endpoint', array('uses' => '\Path\To\Controller@endpoint'));

我确实发现 this question 似乎只在 FireFox 中存在类似问题,但解决方案是用逗号分隔 Allow-Methods,我已经这样做了。

【问题讨论】:

  • 你有 $httpProvider.defaults.withCredentials = true;在 AngularJS .config() 中设置?
  • 我没有。我将它添加到 $http.post() 中的 config 对象中,现在它抱怨 Access-Control-Allow-Origin'*' 不匹配。一些快速研究表明,在使用withCredentials: true 时,我不应该使用'*',但即使将Access-Control-Allow-Origin 更改为http://localhost:8100/#/clientpage(以及我能想到的所有变体),它仍然会返回一个不匹配的错误Access-Control-Allow-Origin 标头。这个概念对我来说是新的,你可以推荐一个很好的最小例子。另外,为什么它之前在其他浏览器中可以工作,而在 FireFox 中不行?
  • “*”通配符可能不起作用
  • 是的,CORS 有点棘手,做一些阅读,你应该能够弄明白。
  • 您找到解决方案了吗?我完全被这个问题困住了。

标签: angularjs firefox laravel ionic-framework cors


【解决方案1】:

消息“缺少令牌'content-type'”是关于客户端的。要使 http 请求成为有效的 post 请求,它必须有一个标头

'Content-Type': 'application/x-www-form-urlencoded' 

'Content-Type': 'multipart/form-data'

第一个内容类型是最常见的。

在 angularjs 中进行 CORS 发布请求的一种方法是

$http.post(
        'http://external-domain.ext/the/rest/url',
        'param_name=param_value',
        {headers:{'Content-Type': 'application/x-www-form-urlencoded'}}
    ).
    then(function successCallback(response) {
       $scope.something = response;
    }, function errorCallback(response) {
       // not good
    });

如果服务器配置有 header('Access-Control-Allow-Origin', '*'),CORS 发布必须在没有身份验证和凭据的情况下成功。

【讨论】:

    【解决方案2】:

    在后端尝试放置

    ->header('Access-Control-Allow-Credentials', 'true')
    

    然后在前端尝试放置

    .config(function($locationProvider, $httpProvider) {
        // CORS requests with credentials
        $httpProvider.defaults.withCredentials = true;
    })
    

    【讨论】:

      猜你喜欢
      • 2021-08-11
      • 2017-11-30
      • 2015-07-01
      • 2015-12-09
      • 1970-01-01
      • 2015-10-30
      • 2013-01-03
      • 1970-01-01
      • 2012-04-25
      相关资源
      最近更新 更多