angularjs-$http.post请求标头字段Access-Control-Allow-Headers错误不允许Access-Control-Allow-Origin

前端之家收集整理的这篇文章主要介绍了angularjs-$http.post请求标头字段Access-Control-Allow-Headers错误不允许Access-Control-Allow-Origin 前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

我正在使用Ionic Framework开发应用程序.

在后端,我为api编写了Flask应用程序,如下所示:

@API.route("/saverez",methods=["POST","OPTIONS"])
@crossdomain(origin='*',headers="*",methods="*")   
@render_api
def saver():
 .....

将json发布到api时出现错误.

var headers = {
                    'Access-Control-Allow-Origin' : '*','Access-Control-Allow-Methods' : 'POST,GET,OPTIONS','Accept': 'application/json'
                };

                $http({
                    method: "POST",headers: headers,url: url+ '/api/saverez',data: $scope.form
                }).success(function (result) 
                    console.log(result);
                }).error(function (data,status,headers,config) {
                    console.log(data);
                    console.log(status);
                    console.log(headers);
                    console.log(config);
                });

所以这给了我错误

XMLHttpRequest cannot load http://myurl/api/saverez. Request header field Access-Control-Allow-Origin is not allowed by Access-Control-Allow-Headers. 

我用谷歌搜索,然后发现以下代码片段:

http://flask.pocoo.org/snippets/56/

我还将标题添加到我的Nginx conf中,如下所示:

location ~* \.(eot|ttf|woff)${
    add_header Access-Control-Allow-Origin *;
}

尝试了该文档中的所有内容以及我在Google上发现的所有东西,但可惜它没有任何好处.

如何为所有来源设置正确的标题?我也使用google pagespeed是否会导致此问题?

提前致谢.

-编辑-
Chrome网络输出

Remote Address:myip
Request URL:http://myurl/api/saverez
Request Method:OPTIONS
Status Code:200 OK
Request Headersview source
Accept:*/*
Accept-Encoding:gzip,deflate,sdch
Accept-Language:en-US,en;q=0.8
Access-Control-Request-Headers:access-control-allow-origin,accept,access-control-allow-methods,content-type
Access-Control-Request-Method:POST
Cache-Control:no-cache
Connection:keep-alive
Host:myurl
Origin:http://192.168.1.46:8100
Pragma:no-cache
Referer:http://192.168.1.46:8100/
User-Agent:Mozilla/5.0 (iPhone; cpu iPhone OS 7_0 like Mac OS X; en-us) AppleWebKit/537.51.1 (KHTML,like Gecko) Version/7.0 Mobile/11A465 Safari/9537.53
Response Headersview source
Access-Control-Allow-Credentials:true
Access-Control-Allow-Headers:*
Access-Control-Allow-Methods:*
Access-Control-Allow-Origin:*
Access-Control-Max-Age:21600
Allow:POST,OPTIONS
Content-Length:0
Content-Type:text/html; charset=utf-8
Date:Thu,28 Aug 2014 13:26:11 GMT
Server:Nginx/1.6.0
最佳答案
在我的应用程序模块配置部分,我有以下内容

angular.module('starterapp',['ionic'])
  .config(function ($stateProvider,$httpProvider,$urlRouterProvider) {

    // We need to setup some parameters for http requests
    // These three lines are all you need for CORS support
    $httpProvider.defaults.useXDomain = true;
    $httpProvider.defaults.withCredentials = true;
    delete $httpProvider.defaults.headers.common['X-Requested-With'];
  }

这就是使所有HTTP请求与CORS一起使用所需要的.当然,这是假设您已经建立了后端.

根据XMLHTTPRequest的w3c规范,您不能添加这些其他标头,因为它们只能由主机浏览器添加.

猜你在找的Nginx相关文章