![](/img/trans.png)
[英]http request with javascript/ajax No 'Access-Control-Allow-Origin'
[英]Ajax - 'Origin localhost is not allowed by Access-Control-Allow-Origin'
我是Ajax的新手,只是受過此跨域調用的任務。 我們的網頁上有一個文本框,用戶將使用該文本框執行公司名稱搜索。 通過單擊文本框旁邊的按鈕,將請求Ajax調用。 不幸的是,Web服務位於單獨的域中,因此自然會引起問題。
以下是我使這項工作的最佳嘗試。 我還要注意,此調用的目的是以XML格式返回結果,該結果將在請求的success
部分中進行解析。
這又是錯誤消息:
Origin http://localhost:55152 is not allowed by Access-Control-Allow-Origin.
對於解決方法,我不知所措,任何想法將不勝感激。
function GetProgramDetails() {
var URL = "http://quahildy01/xRMDRMA02/xrmservices/2011/OrganizationData.svc/AccountSet?$select=AccountId,Name,neu_UniqueId&$filter=startswith(Name,\'" + $('.searchbox').val() + "\')";
var request = $.ajax({
type: 'POST',
url: URL,
contentType: "application/x-www-form-urlencoded",
crossDomain: true,
dataType: XMLHttpRequest,
success: function (data) {
console.log(data);
alert(data);
},
error: function (data) {
console.log(data);
alert("Unable to process your resquest at this time.");
}
});
}
此錯誤是由於跨域資源共享中實施的限制所致。 這已作為安全功能的一部分實現,以通過跨域調用限制資源的客戶端(域)。 當您將請求發送到Web服務或api或類似工具時,它會在服務器或目標(此處是api)的請求中添加Origin標頭,以驗證請求是否來自授權來源。 理想情況下,api /服務器應在接收到的Request header
查找Origin
,並可能針對允許向其提供資源的原始域集進行驗證。 如果來自允許的域,它將在響應標頭中添加與"Access-Control-Allow-Origin"
值相同的域。 也可以使用通配符,但是問題是,通過通配符許可,任何人都可以發出請求並將其送達(有一些限制,例如通過Windows auth或cookie對api進行身份驗證,而您需要發送withCredentials
值*
是不允許)。 使用通配符來源的響應標頭不是一個好習慣,因為它對所有人開放。
這些是使用值設置響應頭的方法:-
Access-Control-Allow-Origin: *
Access-Control-Allow-Origin: http://yourdomain.com
您甚至可以在同一響應中添加多個Access-Control-Allow-Origin標頭(我相信在大多數瀏覽器中都可以使用)
Access-Control-Allow-Origin: http://yourdomain1.com
Access-Control-Allow-Origin: http://yourdomain2.com
Access-Control-Allow-Origin: http://yourdomain3.com
在服務器端(c#語法),您可以這樣做:
var sourceDomain = Request.Headers["Origin"]; //This gives the origin domain for the request
Response.AppendHeader("Access-Control-Allow-Origin", sourceDomain ); //Set the response header with the origin value after validation (if any) .Depending on the type of application you are using syntax may vary.
希望這可以幫助!!!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.