問題描述
我正在嘗試實(shí)現(xiàn)簡單的 xhr 抽象,并在嘗試為 POST 設(shè)置標(biāo)頭時收到此警告.我認(rèn)為這可能與在單獨(dú)的 js 文件中設(shè)置標(biāo)題有關(guān),因?yàn)楫?dāng)我在 .html 文件的 <script>
標(biāo)記中設(shè)置它們時,它工作正常.POST 請求工作正常,但我收到此警告,我很好奇為什么.對于 content-length
和 connection
標(biāo)頭,我都會收到此警告,但僅限于 WebKit 瀏覽器(Chrome 5 beta 和 Safari 4).在 Firefox 中,我沒有收到任何警告,Content-Length 標(biāo)頭設(shè)置為正確的值,但 Connection 設(shè)置為 keep-alive 而不是 close,這讓我認(rèn)為它也忽略了我的 setRequestHeader 調(diào)用并生成它自己的.我沒有在 IE 中嘗試過這段代碼.這是標(biāo)記和代碼:
I am trying to implement simple xhr abstraction, and am getting this warning when trying to set the headers for a POST. I think it might have something to do with setting the headers in a separate js file, because when i set them in the <script>
tag in the .html file, it worked fine. The POST request is working fine, but I get this warning, and am curious why. I get this warning for both content-length
and connection
headers, but only in WebKit browsers (Chrome 5 beta and Safari 4). In Firefox, I don't get any warnings, the Content-Length header is set to the correct value, but the Connection is set to keep-alive instead of close, which makes me think that it is also ignoring my setRequestHeader calls and generating it's own. I have not tried this code in IE. Here is the markup & code:
test.html
:
<!DOCTYPE html>
<html>
<head>
<script src="jsfile.js"></script>
<script>
var request = new Xhr('POST', 'script.php', true, 'data=somedata', function(data) {
console.log(data.text);
});
</script>
</head>
<body>
</body>
</html>
jsfile.js
:
function Xhr(method, url, async, data, callback) {
var x;
if(window.XMLHttpRequest) {
x = new XMLHttpRequest();
x.open(method, url, async);
x.onreadystatechange = function() {
if(x.readyState === 4) {
if(x.status === 200) {
var data = {
text: x.responseText,
xml: x.responseXML
};
callback.call(this, data);
}
}
}
if(method.toLowerCase() === "post") {
x.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
x.setRequestHeader("Content-Length", data.length);
x.setRequestHeader("Connection", "close");
}
x.send(data);
} else {
// ... implement IE code here ...
}
return x;
}
推薦答案
它也忽略了我的 setRequestHeader 調(diào)用并生成它自己的
it is also ignoring my setRequestHeader calls and generating its own
是的,標(biāo)準(zhǔn)說它必須:
出于安全原因,如果標(biāo)題為 [...],則應(yīng)終止這些步驟
For security reasons, these steps should be terminated if header is [...]
- 連接
- 內(nèi)容長度
搞砸這些可能會暴露各種請求走私攻擊,所以瀏覽器總是使用自己的價值觀.沒有必要也沒有理由嘗試設(shè)置請求長度,因?yàn)闉g覽器可以根據(jù)您傳遞給 send()
的數(shù)據(jù)長度準(zhǔn)確地做到這一點(diǎn).
Messing around with those could expose various request smuggling attacks, so the browser always uses its own values. There's no need or reason to try to set the request length, as the browser can do that accurately from the length of data you pass to send()
.
這篇關(guān)于WebKit “拒絕設(shè)置不安全的標(biāo)頭‘內(nèi)容長度’"的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!