2015-03-25 48 views
1

我正在嘗試請求使用Codeigniter 3編碼的RestAPI。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 
     } 
    }); 
} 

這段代碼不起作用。谷歌瀏覽器控制檯顯示我:

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

,並在網絡選項卡則說明該請求使用的方法類型「選項」,而不是一個「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 

原諒我,如果我的英語是不正確的。

非常感謝。

回答

0

你應該添加頁眉與此:

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

你可以在一些配置爲全局添加。

+0

在功能上它是一樣的,我這樣做是爲了測試代碼。我稍後會改變它。 – 2015-03-25 19:26:06