Javascript AJAX 发布错误:拒绝设置不安全的标头“连接”

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7210507/
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-08-24 01:21:49  来源:igfitidea点击:

AJAX post error : Refused to set unsafe header "Connection"

javascriptajax

提问by sniper

I have the following custom ajax function that posts data back to a PHP file. Everytime the post of data happens I get the following two errors :

我有以下自定义 ajax 函数,可将数据发回 PHP 文件。每次发布数据时,我都会收到以下两个错误:

Refused to set unsafe header "Content-length"
Refused to set unsafe header "Connection"

拒绝设置不安全标头“Content-length”
拒绝设置不安全标头“Connection”

Code :

代码 :

function passposturl(url1, params, obj)
{
    //url1 = url1+"&sid="+Math.random();
    xmlHttp = get_xmlhttp_obj();
    xmlHttp.loadflag = obj;
    xmlHttp.open("POST", url1, true);
    //alert(url1);
    //alert(params);
    //alert(obj);
    //alert(params.length);
    xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    xmlHttp.setRequestHeader("Content-length", params.length);
    xmlHttp.setRequestHeader("Connection", "close");
    xmlHttp.onreadystatechange = function ()
    {
        stateChanged(xmlHttp);
    };
    xmlHttp.send(params);
 }

What am I doing wrong?

我究竟做错了什么?

回答by Wladimir Palant

Remove these two lines:

删除这两行:

xmlHttp.setRequestHeader("Content-length", params.length);
xmlHttp.setRequestHeader("Connection", "close");

XMLHttpRequest isn't allowed to set these headers, they are being set automatically by the browser. The reason is that by manipulating these headers you might be able to trick the server into accepting a second request through the same connection, one that wouldn't go through the usual security checks - that would be a security vulnerability in the browser.

XMLHttpRequest 不允许设置这些标头,它们是由浏览器自动设置的。原因是通过操纵这些标头,您可能能够欺骗服务器通过同一连接接受第二个请求,该请求不会通过通常的安全检查 - 这将是浏览器中的安全漏洞。