【问题标题】:XMLHttpRequest for http:// required Cross Origin Resource Sharing (CORS) and preflight only happen in IEhttp:// 的 XMLHttpRequest 需要跨域资源共享 (CORS) 和预检仅在 IE 中发生
【发布时间】:2013-12-08 05:27:03
【问题描述】:

我是一名前端开发人员。我只在客户端编码,所以我不确定是否存在错误。我一直在搜索 CORS,但仍然不知道我的问题是什么。

我正在尝试将数据发布到 REST。

$.ajax({
     url        : urlPost,
     type       : "POST",
     data       : JSON.stringify(obj),
     dataType   : "json",
     contentType: "application/json",

     success: function(res){
         console.log(JSON.stringify(res));
     },

     error: function(res){
         console.log("Bad thing happend! " + res.statusText);
     }
});

firefox 的 firebug 中显示 web 服务的标头:

它适用于我使用的所有浏览器,除了在 IE 10 中,我遇到两个错误:

  1. SEC7118:http://mysite/project/wl.svc/AddWL/ 的 XMLHttpRequest 需要跨源资源共享 (CORS)。

  2. SEC7119:http://mysite/project/wl.svc/AddWL/ 的 XMLHttpRequest 需要 CORS 预检。

【问题讨论】:

  • urlPost 是否与加载文档的域相同?你在使用 SSL 吗?文档在 IFRAME 内吗?在任何情况下,CORS 都需要来自服务器的特殊标头才能工作。不能只从客户端配置。
  • 但我想知道,它适用于 Chrome、Firefox(IE 除外)。
  • urlPost 与文档加载域在不同的域中。我用标题更新了我的问题。
  • jQuery 不支持 IE

标签: javascript ajax


【解决方案1】:

我想你有一个CORS,所以我建议你看看cors-anywhere

我已经使用了它,它可以很好地满足您将请求 URL 附加到 https://cors-anywhere.herokuapp.com/ 所需的一切,它是请求所选 URL 的代理服务器

var cors_api_url = 'https://cors-anywhere.herokuapp.com/' + urlPost;

$.ajax({
     url        : cors_api_url,
     type       : "POST",
     data       : JSON.stringify(obj),
     dataType   : "json",
     contentType: "application/json",

     success: function(res){
         console.log(JSON.stringify(res));
     },

     error: function(res){
         console.log("Bad thing happend! " + res.statusText);
     }
});

【讨论】:

    猜你喜欢
    • 2013-05-29
    • 2013-01-12
    • 2014-03-20
    • 1970-01-01
    • 2018-05-04
    • 2011-06-10
    • 2013-11-01
    • 1970-01-01
    • 2013-01-18
    相关资源
    最近更新 更多