我在互聯網上做了一些研究,但是我沒有設法獲得關於這個主題的完整圖片。任何人都可以幫助解決這個問題,現在和永遠?我可以在跨域json請求中設置標題嗎?
這是我迄今發現:
- 這是可以做到跨域調用與JSONP。從不允許更改jsonp調用中的標頭
- 如果服務器允許,可以使用json進行跨域調用。
這就是我要做的:
$.ajax({
type: "GET",
crossDomain: true,
beforeSend: function (request) {
request.setRequestHeader("Authorization", "Bearer " + ($("#accesstoken").val()));
},
contentType: "application/json; charset=utf-8",
url: myJSonServer + encodeURI(operation),
dataType: 'json',
cache: false,
success: callback,
error: function (jqXhr, textStatus, errorThrown) { alert(textStatus + ": " + errorThrown); }
});
這是正在發生的事情:
- 當myJSonServer是在同一個域中,在所有 沒問題
- 當myJSonServer在另一個域上時,發送請求,但沒有承載頭
這個承載頭是oAuth2標準的一部分。
我意識到這樣的事實,可能這不是最好的解決方案,在瀏覽器中設置accessToken。而且我知道我可以使用代理來處理這種情況。
我只是好奇,如果它是或將有可能在跨域json請求上設置標頭?
感謝
- 問題解決
我使用MVC4並在web.config中添加crossDomainScriptAccessEnabled = 「真」。我認爲這足夠了,但是撲克玩家的答案解決了我的問題。現在我已經在我的web.config中添加此:
<system.webServer>
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*" />
<add name="Access-Control-Allow-Headers" value="Authorization" />
</customHeaders>
</httpProtocol>
</system.webServer>
[可能與jquery.ajax()交叉來源'授權'標題的副本(http://stackoverflow.com/questions/9559947/cross-origin-authorization-header-with-jquery-ajax)。 – apsillers