Access-Control-Allow-Origin'不允许使用Ajax - '

本文关键字:Ajax 不允许 Access-Control-Allow-Origin | 更新日期: 2023-09-27 18:04:52

我对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.");
        }
    });
}

Access-Control-Allow-Origin'不允许使用Ajax - '

此错误是由于在跨域资源共享中强制执行的限制造成的。这已经作为安全特性的一部分实现,通过跨域调用来限制资源的客户端(域)。当您向web服务或api或类似的请求发送请求时,它会在服务器或目的地(这里是您的api)的请求中添加Origin头,以验证请求是否来自授权源。理想情况下,api/服务器应该在它收到的Request header中查找Origin,并可能根据允许为其提供资源的一组起源(域)进行验证。如果它来自一个允许的域,它将在响应头中添加与"Access-Control-Allow-Origin"值相同的域。通配符也是允许的,但问题是,有了通配符权限,任何人都可以发出请求并得到服务(有一些限制,比如api通过windows认证或cookie进行身份验证,你需要发送withCredentials值,*是不允许的)。使用通配符origin作为响应头并不是一个好的做法,这会使它对所有人开放。

以下是设置响应头的一些方法:-

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.

希望这有帮助!!