【问题标题】:Send JSON POST request to external domain without having access to the server向外部域发送 JSON POST 请求,而无需访问服务器
【发布时间】:2017-04-06 03:21:03
【问题描述】:

我正在尝试在JSON 中向外部域发出POST 请求,但我无法访问服务器的文件来修改它们。

当我执行此请求时,我收到以下错误

XMLHttpRequest 无法加载 https://external.com。不 'Access-Control-Allow-Origin' 标头出现在请求的 资源。原点 'https://www.ownedwebsite.com' 因此不是 允许访问。

问题出在哪里?

这是我正在使用的代码:

  $(document).ready(function(){
            $("#submit").on('click', function(){
                event.preventDefault();
                $.ajax({
                    url: 'https://external.com',
                    type : "POST",
                    crossDomain: true,
                    dataType : 'json',
                    beforeSend: function (request)
                    {
                    //request.setRequestHeader("name", "value");
                    },
                    data : $("#formCart").serialize(),
                    success : function(result) {
                    alert('POST done.');
                    },
                    error: function(xhr, resp, text) {
                        alert('POST failed.');
                    }
                })
            });
        });

我能做什么?我需要做的就是以 JSON 格式发送这个 POST 表单数据。

【问题讨论】:

  • 致电 external.net 的提供者并要求他们将您添加到他们的 CORS 标头中
  • 我需要在无法修改 CORS 标头等的情况下执行请求。所以不,我不能“调用提供者”@madalinivascu
  • 提供者是否允许您使用此资源,您查看过他们的文档吗?
  • 提供商只是我公司的一个测试网站,但我想在服务器端不启用 CORS 标头的情况下执行请求,因为服务器站点上的其他问题使得这不可能@madalinivascu跨度>

标签: jquery html json ajax cross-domain


【解决方案1】:

如果您想从twitter 获取json 数据,您必须注册api 密钥,这意味着它们已准备好使用json 提供服务,类似的方法适用于其他站点。

如果您只是想抓取页面,那么您可以使用heroku api 来实现

$(document).ready(function(){
      var text = 'https://login.yahoo.com/';
      $.ajaxPrefilter( function (options) {
        if (options.crossDomain && jQuery.support.cors) {
          var http = (window.location.protocol === 'http:' ? 'http:' : 'https:');
          options.url = http + '//cors-anywhere.herokuapp.com/' + options.url;
          //options.url = "http://cors.corsproxy.io/url=" + options.url;
        }
      });

      $.get(
          'https://en.wikipedia.org/wiki/Thomas_Alva_Edison_Memorial_Tower_and_Museum',
          function (response) {

          var res = response;
           $('#yahoo').append(res);


      });

  });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
<div id="yahoo"></div>

【讨论】:

  • 我需要向它发送一个 POST 请求,而不仅仅是获取页面。
  • 注册 api 密钥,以便他们将标头设置为 allow your site
  • 否则使用'cURL` 可以登录到其他网站这是POST的示例
  • 所以我注册到 api 并调用此链接,它将作为我想查询的外部站点的镜像站点工作,但同时允许我创建 CORS 请求? @EaBangalore
猜你喜欢
  • 2016-07-03
  • 1970-01-01
  • 1970-01-01
  • 2012-12-12
  • 1970-01-01
  • 2014-09-02
  • 1970-01-01
  • 2020-02-16
  • 1970-01-01
相关资源
最近更新 更多