AngularJS - 无法在$ http请求上传递标头

时间:2015-03-25 01:50:40

标签: angularjs codeigniter http

我正在尝试向使用Codeigniter编码的RestAPI发出请求3. Access-Control-Allow-Origin和Access-Control-Allow-Headers设置为“*”。该API已在Postman上成功测试。

我正在使用AngularJS编写Web应用程序,并尝试向该API发出请求。以下代码正常运行:

api_service.getUsers = function() {

    return $http({
        method : 'GET',
        url : url + '?dd-api-key=' + api_key
    });

}

正如其他代码也能很好地运作:

api_service.getUsers = function() {

    return $http.get(url + '?dd-api-key=' + api_key);

}

但我需要将API密钥作为标头发送,而不是在URL中。所以我用这种方式写了这个函数:

api_service.getUsers = function() {

    return $http({    
        method: 'GET',
        url: url,
        headers: {
            'accept': undefined,
            'dd-api-key': api_key
        }
    });
}

该代码不起作用。 Google Chrome控制台向我展示了这一点:

OPTIONS http://www.myweb.com/api/v1/users
XMLHttpRequest cannot load http://www.myweb.com/api/v1/users. Invalid HTTP status code 403 

在网络选项卡中,它显示请求使用方法类型'OPTIONS',而不是'GET'方法。

响应标题是:

Access-Control-Allow-Headers:*
Access-Control-Allow-Methods:PUT, GET, POST, DELETE, OPTIONS
Access-Control-Allow-Origin:*
Cache-Control:no-store, no-cache, must-revalidate, post-check=0, pre-check=0
Connection:keep-alive
Content-Language:es-ES
Content-Length:45
Content-Type:application/json; charset=utf-8
Date:Wed, 25 Mar 2015 01:45:09 GMT
Expires:Thu, 19 Nov 1981 08:52:00 GMT
Pragma:no-cache
Server:nginx/1.6.2

请求标题是:

Accept:*/*
Accept-Encoding:gzip, deflate, sdch
Accept-Language:es-ES,es;q=0.8,en;q=0.6
Access-Control-Request-Headers:dd-api-key
Access-Control-Request-Method:GET
Connection:keep-alive
Host:www.myweb.com
Origin:http://127.0.0.1:55652
Referer:http://127.0.0.1:55652/index.html
User-Agent:Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.101 Safari/537.36

如果我的英语不正确,请原谅。

非常感谢。

1 个答案:

答案 0 :(得分:0)

你应该用这个添加标题:

$http.defaults.headers.common.dd-api-key = api_key;

您可以将其添加到某个配置中作为全局。