Ajax - '访问控制 - 允许来源'不允许访问本地主机'

问题描述:

我对Ajax比较陌生,只是负责这个跨域调用。我们在我们的网页上有一个文本框,用户将用它来搜索公司名称。通过单击文本框旁边的按钮,将会请求Ajax调用。不幸的是,Web服务位于一个单独的域中,所以这自然会造成问题。Ajax - '访问控制 - 允许来源'不允许访问本地主机'

以下是我做这项工作的最佳尝试。我还应该注意到,此调用的目的是以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."); 
     } 
    }); 
} 
+2

尝试在您的响应标题中添加Access-Control-Allow-Origin:*。 – PSL 2013-03-20 21:07:04

+0

你能提供一个如何做的例子吗? – NealR 2013-03-20 21:21:12

+1

好的。这是c#code.Try Response.AppendHeader(“Access-Control-Allow-Origin”,Request.Headers [“Origin”]);或Response.AppendHeader(“Access-Control-Allow-Origin”,“*”); – PSL 2013-03-20 22:13:43

此错误是由于在跨域资源共享中强制实施的限制。这已作为安全功能的一部分实施,以通过跨域调用来限制资源的客户端(域)。当您向webservice或api或类似服务器发送请求时,会在服务器或目标(此处为api)的请求中添加Origin标头,以验证请求是否来自授权源。理想情况下,API /服务器应该在收到的Request header中查找Origin,并且可能会根据允许服务资源的源(域)集合进行验证。如果它来自允许的域,它将在响应头中添加与"Access-Control-Allow-Origin"值相同的域。通配符也是允许的,但问题在于,通配符允许任何人发出请求并获得服务(像api一样的限制通过Windows身份验证或cookie进行身份验证,您需要发送withCredentials*不允许)。使用通配符来源并不是一个很好的做法,它使响应标题向所有人开放。

这些都是一些方法来设置响应的文件头和值: -

Access-Control-Allow-Origin: * 
Access-Control-Allow-Origin: http://yourdomain.com 

你甚至可以在同一个响应添加多个访问控制允许来源头(我相信在大多数浏览器的作品)

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. 

希望这有助于!

+0

我猜''“Origin”]'将是相同的http:// yourdomain.com' ? (在我的情况下,这将是'http:// localhost:55152') – NealR 2013-03-21 15:49:02

+0

是的。您可以通过调试Request.Headers [“Origin”]或使用fiddler在您的请求中查找标头来确认它在您的服务器代码中。 – PSL 2013-03-21 15:51:14

+1

要写这个文件的哪个文件?或者在哪里写这个没有提到。 – 2015-10-15 15:44:27