gpt4 book ai didi

c# - Ajax - 'Origin localhost is not allowed by Access-Control-Allow-Origin'

转载 作者:太空狗 更新时间:2023-10-30 00:53:37 28 4
gpt4 key购买 nike

我是 Ajax 的新手,刚接到这个跨域调用的任务。我们的网页上有一个文本框,用户将使用它来执行公司名称搜索。通过单击文本框旁边的按钮,将请求 Ajax 调用。不幸的是,Web 服务位于一个单独的域中,因此这自然会导致问题。

以下是我为完成这项工作所做的最佳尝试。我还应该注意,此调用的目的是以 XML 格式返回结果,该格式将在请求的 success 部分进行解析。

再次出现错误信息:

Access-Control-Allow-Origin 不允许来源 http://localhost:55152。

我不知道该怎么做才能解决问题,我们将不胜感激任何想法。

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 header ,以验证请求是否来自授权源。理想情况下,api/服务器应该在它接收到的 Request header 中查找 Origin,并可能根据允许向其提供资源的来源(域)集进行验证.如果它来自允许的域,它将在响应 header 中添加与 "Access-Control-Allow-Origin" 值相同的域。也允许使用通配符,但问题是有了通配符许可,任何人都可以发出请求并得到它的服务(有一些限制,比如 api 通过 Windows 身份验证或 cookie 进行身份验证,您需要在其中发送 withCredentials * 是不允许的)。在响应 header 中使用通配符并不是一个好习惯,因为它对所有人开放。

这些是用值设置响应 header 的一些方法:-

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

您甚至可以在同一响应中添加多个 Access-Control-Allow-Origin header (我相信在大多数浏览器中都适用)

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.

希望这有帮助!!!

关于c# - Ajax - 'Origin localhost is not allowed by Access-Control-Allow-Origin',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15534640/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com