【问题标题】:Post JSON data to external URL将 JSON 数据发布到外部 URL
【发布时间】:2013-04-05 00:31:04
【问题描述】:

如何将 JSON 数据作为 url 字符串发布到外部 url(跨域)并绕过访问控制?

这是一个 jquery .ajax 发布请求,由于 Access-Control-Allow-Origin 的原因,它无法发送到外部 url:

var json = JSON.stringify(object);

$.ajax({
  type: 'POST',
  url: externalurl,
  data: json,
  dataType: 'json',
  success: function(data){console.log(data);},
  failure: function(errMsg) {
      console.log(errMsg);
  },
});

我收到了将数据发布到同一个域并将“请求传递”到外部域的建议,尽管这个解决方案对我来说没有意义。我正在寻找最安全的解决方案。任何帮助将不胜感激。

【问题讨论】:

  • 您尝试过使用 JSON-P 吗?我相信在 jQuery 中你使用 'jsonp' 而不是 'json' 作为数据类型这样做,但我不是 100% 确定...
  • 当您说“传递请求”解决方案对您没有意义时,您的意思是您不理解它并想要一个解释,或者您确实理解它但认为不适合你现在的情况? @MarkOrmston - JSONP 确实可以让您解决域问题,但它只有在设置外部域来处理它并提供适当的响应时才有效。
  • 是的,这种情况不适合,数据必须以json的形式发送。我也无法控制外部服务器,因此 CORS 也不是一个可能的解决方案。
  • @jverban 如果您无法控制其他域服务,则可能无法从中获得响应。可能看看这个..stackoverflow.com/questions/15534640/…
  • 好的,我不明白为什么您认为以 JSON 格式发送的数据会阻止您执行“传递请求”的操作。您的 jQuery 将向您自己的 PHP 发出 Ajax 请求,而您的 PHP 将调用其他服务器,然后获取其响应并将其返回给浏览器。无论有没有 JSON,这都是可行的......

标签: php javascript jquery json post


【解决方案1】:

我不久前在 PHP 中做过这个。这是“传递请求”的示例。 (您需要启用 PHP cURL,这是大多数安装的标准配置。)

<?php
    //Get the JSON data POSTed to the page
    $request = file_get_contents('php://input');

    //Send the JSON data to the right server
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, "http://location_of_server.com/");
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type: application/json; charset=utf-8"));
    curl_setopt($ch, CURLOPT_POSTFIELDS, $request);
    $data = curl_exec($ch);
    curl_close($ch);

    //Send the response back to the Javascript code
    echo $data;
?>

【讨论】:

  • 非常感谢您的解决方案。
【解决方案2】:

绕过同源策略的一种方法是使用 cURL 进行实际传输。

我将给出一个使用 PHP 的示例,但是您可以在任何服务器端语言上轻松地做到这一点。

在你的服务器上设置一个脚本,例如 send.php

首先你把你的ajax指向send.php

var json = JSON.stringify(object);

$.ajax({
    type: 'POST',
    url: send.php,
    data: json,
    dataType: 'json',
    success: function(data){console.log(data);},
    failure: function(errMsg) {
        console.log(errMsg);
    },
});

然后你的php脚本转发它:

<?php
    // Initialize curl
    $curl = curl_init();

    // Configure curl options
    $opts = array(
        CURLOPT_URL             => $externalscriptaddress,
        CURLOPT_RETURNTRANSFER  => true,
        CURLOPT_CUSTOMREQUEST   => 'POST',
        CURLOPT_POST            => 1,
        CURLOPT_POSTFIELDS      => 'field1=arg1&field2=arg2'
    );

    // Set curl options
    curl_setopt_array($curl, $opts);

    // Get the results
    $result = curl_exec($curl);

    // Close resource
    curl_close($curl);

    echo $result;
?>

【讨论】:

  • 很高兴为您提供帮助,如果您对解决方案感到满意,请将其标记为其他人将来看到的答案。
  • 要接受答案,您可以点击赞成票旁边的勾号,它会将答案标记为正确答案,如果您的第一个问题标记为答案,也会给您一些声誉:)
  • 啊,不知道怎么做 - stackoverflow 还是新手。再次感谢
猜你喜欢
  • 1970-01-01
  • 2019-01-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多