【问题标题】:Jquery Ajax to Web Api CORS is not workingJquery Ajax 到 Web Api CORS 不起作用
【发布时间】:2014-01-01 04:55:55
【问题描述】:

我有以下 jquery 代码

 $('#spam').click(function () {
    $.ajax({
        type: 'GET',
        url: 'http://www.my-contacts.com/contacts/api/contacts',
        dataType: 'json',
        contentType: 'application/json; charset=utf-8',
        headers: { 'Authorization=': 'Bearer ' },

    }).done(function () {
        alert("success");
    })
.fail(function (xhr, textStatus, errorThrown) {
    console.log(xhr);
    alert("Error:" + xhr);
});
});

浏览器发送带有选项的预检请求并从服务器获得 200(我已经安排了一个被调用的处理程序)。以下是标题

**Response Headers view source**
Access-Control-Allow-Head...    Authorization, X-Authorization
Access-Control-Allow-Meth...    GET, POST, PUT, DELETE, HEAD, OPTIONS
Access-Control-Allow-Orig...    *
Cache-Control   no-cache
Content-Length  0
Date    Fri, 13 Dec 2013 12:01:18 GMT
Expires -1
Pragma  no-cache
Server  Microsoft-IIS/7.5
X-AspNet-Version    4.0.30319
X-Powered-By    ASP.NET

**Request Headers view source**
  Accept    text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
  Accept-Encoding   gzip, deflate
  Accept-Language   en-US,en;q=0.5
  Access-Control-Request-He...  content-type
  Access-Control-Request-Me...  GET
  Connection    keep-alive
  Host  www.my-contacts.com
  Origin    http://www.my-promo.com
  User-Agent    Mozilla/5.0 (Windows NT 6.1; WOW64; rv:25.0) Gecko/20100101 Firefox/25.0

问题是浏览器应该继续 GET 请求,但没有任何反应,我从 .error() Jquery 代码中收到错误消息。

任何指针?

编辑

事实证明,上述方法不起作用的原因有很多。然而,最终归结为 JQuery 不能很好地与 CORS 配合使用(至少我使用的版本是 1.8.2,但我也尝试过 1.10)

我用

更改了代码
(function () {
            x = new XMLHttpRequest();
            x.open('GET', 'http://www.my-contacts.com/contacts/api/contacts', false);
            x.onreadystatechange = function () {
                if (x.readyState === 4) {
                    console.info(x.responseText);
                }
            };
            x.setRequestHeader("Content-Type", "text/plain;charset=UTF-8");
            x.setRequestHeader('Authorization', 'Bearer ' + accessToken);
            x.send('');
        })();

但此代码不适用于 IE 或 FF。另一方面,Chrome 可以完美运行。另外两个给我x.send('')的错误

【问题讨论】:

  • 你有更多关于.fail中的xhr对象、textStatus和errorThrown的细节吗?
  • 在使用 ajax 尝试之前,我总是使用一些工具(fiddler、postman rest 客户端)尝试 API 请求。

标签: jquery cors asp.net-web-api


【解决方案1】:

如果不查看服务的配置,很难说出问题所在。让这个工作真的很棘手。这个链接对我有很大帮助。他正在配置 WCF 服务,但我认为它值得一读..

Implementing CORS support in WCF

【讨论】:

    猜你喜欢
    • 2016-09-23
    • 2017-07-05
    • 2015-11-14
    • 1970-01-01
    • 1970-01-01
    • 2014-05-01
    • 2019-01-15
    • 1970-01-01
    相关资源
    最近更新 更多