我正在嘗試對iContact API執行一個請求,該請求需要我使用自定義標頭進行驗證(http://developer.icontact.com/documentation/authenticate-requests)。這是我的代碼:jQuery AJAX自定義標頭
$.ajax({
type: "GET",
url: "https://app.icontact.com/icp/a/",
contentType: "application/json",
beforeSend: function(jqXHR, settings){
jqXHR.setRequestHeader("Accept", "application/json");
jqXHR.setRequestHeader("Api-Version", iContact_API_version);
jqXHR.setRequestHeader("Api-AppId", iContact_appID);
jqXHR.setRequestHeader("Api-Username", iContact_username);
jqXHR.setRequestHeader("API-Password", iContact_appPassword);}
});
由於某種原因,請求沒有通過。但是,當我手動執行相同的請求(使用Chrome REST控制檯)時,它工作得很好。如果我取出自定義標頭(API- *),請求會通過,但當然身份驗證會失敗,並返回一個常規的HTML頁面。
我切換到Firefox和檢查請求/響應頭:
請求:
Host app.icontact.com
User-Agent Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.6; en-US; rv:1.9.2.12) Gecko/20101026 Firefox/3.6.12
Accept text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language en-us,en;q=0.5
Accept-Encoding gzip,deflate
Accept-Charset ISO-8859-1,utf-8;q=0.7,*;q=0.7
Keep-Alive 115
Connection keep-alive
Origin http://184.72.61.244
Access-Control-Request-Me... GET
Access-Control-Request-He... api-appid,api-password,api-username,api-version
響應:
HTTP/1.1 302 Found
Date: Tue, 14 Jun 2011 23:43:56 GMT
Server: Apache/2.2.9 (Debian)
Set-Cookie: intellicontact_phpsess=1c7ca333017b47f46edd893dae584781; path=/; domain=.icontact.com; secure; HttpOnly
Expires: Thu, 19 Nov 1981 08:52:00 GMT
Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0
Pragma: no-cache
Location: https://app.icontact.com/icp/login/sentry.php?relurl=https%3A%2F%2Fapp.icontact.com%2Ficp%2Fa%2F&sess=
Vary: Accept-Encoding
Content-Encoding: gzip
Content-Length: 20
Connection: close
Content-Type: text/html; charset=utf-8
任何想法是怎麼回事錯在這裏?
謝謝!
你可能看一個OPTIONS請求,這是尋找目標主機是否允許跨域請求,[詳細](http://stackoverflow.com/questions/1256593/ jQuery的,爲什麼-AM-I-得到-的選項,請求insted的-的-A-獲得請求)。解決方法是使用JSONP,但這不支持自定義標頭,[這是爲什麼](http://stackoverflow.com/questions/3350778/modify-http-headers-for-a-jsonp-request)。如果iContact不支持跨域ajax請求或JSONP,最終可能會使用[cURL](http://en.wikipedia.org/wiki/CURL)等。 – 2012-08-28 14:12:58
[JSON Post with Customized HTTPHeader Field]的可能重複(http://stackoverflow.com/questions/7100294/json-post-with-customized-httpheader-field) – JAAulde 2014-02-20 01:12:28
http://stackoverflow.com/a/14655768/ 1581725 – 2015-04-18 01:19:12