javascript 如何修复 Firefox 中的跨域请求失败

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/33118900/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 16:08:44  来源:igfitidea点击:

How to fix cross-origin request fail in Firefox

javascriptjson.htaccessfirefox

提问by YdB

I have a javascript file in which i want to send json data to a ERP system:

我有一个 javascript 文件,我想在其中将 json 数据发送到 ERP 系统:

 var formData1 = JSON.stringify($('#msform').serializeObject());
    $.ajax({
        url:'http://102.101.101.11:80/cops.nsf/orders?openagent',
        type:'POST',
        data:formData1,
        crossDomain: true,
        dataType: 'json',
        jsonpCallback: 'callback',
        success: function(data) {
            //window.location.href = "http://www.petlooza.com";
            console.log(data);
        }
    });

This script works with chrome and IE, but FIREFOX gives me this error:

这个脚本适用于 chrome 和 IE,但 FIREFOX 给了我这个错误:

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at the url. Reason: Cors-request failed.

跨域请求被阻止:同源策略不允许读取 url 上的远程资源。原因:Cors 请求失败。

How to fix this? See solution below!

如何解决这个问题?请参阅下面的解决方案!

采纳答案by YdB

I fixed it by doing the following:

我通过执行以下操作修复了它:

A. You need a .htaccess on the host where you run the script.

答:您需要在运行脚本的主机上有一个 .htaccess。

<FilesMatch "\.(php)$">
  <IfModule mod_headers.c>
    Header set Access-Control-Allow-Origin "*"
  </IfModule>
</FilesMatch>

Header set Access-Control-Allow-Origin "*"
Header set Access-Control-Allow-Methods "POST, GET, OPTIONS"
Header set Access-Control-Max-Age "1000"
Header set Access-Control-Allow-Headers "x-requested-with, Content-Type, origin, authorization, accept, client-security-token"

secondly the ERP system also need headers to be set. You can check with curl if headers are correctly set or not.

其次ERP系统也需要设置抬头。您可以使用 curl 检查标题是否正确设置。

B. Another option: if you do not want to work with headers, or are unable to set some headers then you can use CURL to do the job :

B. 另一种选择:如果您不想使用标题,或者无法设置某些标题,那么您可以使用 CURL 来完成这项工作:

when clicking submit on my form, my script will call a .php file in which i have this code:

单击表单上的提交时,我的脚本将调用一个 .php 文件,其中包含以下代码:

<?php
//
//code to send json to lotus webservice without cors errors
//
$jsondata = $_GET['jsondata'];
$ch = curl_init();

curl_setopt($ch, CURLOPT_URL,"102.101.101.11:80/cops.nsf/orders?openagent");
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS,$jsondata);

// in real life you should use something like:
// curl_setopt($ch, CURLOPT_POSTFIELDS,
//          http_build_query(array('postvar1' => 'value1')));

// receive server response ...
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

$server_output = curl_exec ($ch);


curl_close ($ch);



?>

and it works! no more cors errors! and data send to the server and also received by server :)

它有效!没有更多的 cors 错误!和数据发送到服务器,也由服务器接收:)

回答by Grey Hodge

I'd suggest checking out the following resources:

我建议查看以下资源:

Firefox CORS request giving 'Cross-Origin Request Blocked' despite headerswhich is a StackOverflow question from a bit ago.

Firefox CORS 请求给出了“跨源请求被阻止”,尽管标题是不久前的 StackOverflow 问题。

https://developer.mozilla.org/en-US/docs/Web/Security/Same-origin_policyMight help you debug your issue, it demonstrates how Mozilla has implemented their own security policy on CORS.

https://developer.mozilla.org/en-US/docs/Web/Security/Same-origin_policy可能会帮助您调试问题,它演示了 Mozilla 如何在 CORS 上实施自己的安全策略。

https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORSis a mroe in depth server side document about Mozilla's CORS implementation.

https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS是一个关于 Mozilla 的 CORS 实现的深度服务器端文档。

It could be you're requesting it via a different protocol or host, which we can't tell from your examples here, but are common failure modes.

可能是您通过不同的协议或主机请求它,我们无法从您的示例中看出这一点,但这是常见的故障模式。

回答by Karl-Henry Martinsson

If you have control of the code on the other side, you can use JSONP instead to get the data, and can avoid all the issues with CORS.

如果您可以控制另一端的代码,则可以改用 JSONP 来获取数据,并且可以避免 CORS 的所有问题。

Update:I blogged about JSONP the other day: http://blog.texasswede.com/calling-a-notes-web-agent-from-another-server-using-jsonp/

更新:前几天我写了一篇关于 JSONP 的博客:http: //blog.texasswede.com/calling-a-notes-web-agent-from-another-server-using-jsonp/