【发布时间】:2018-07-15 10:43:35
【问题描述】:
我想在我的服务器上读取同一子域中的文件并显示其内容。我在XMLHttpRequest asynchronous not working, always returns status 0 上看到过类似的问题,除了在我的情况下,所有文件都在我的服务器上并且在同一个子域(甚至是同一个目录)内,而且我不想劫持别人的线程。
我的服务器上有三个文件:
counter.txt:
1234
加载文件.js:
function loadFile(filePath) {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("output").innerHTML = this.responseText;
} else {
debug = 'readyState=' + this.readyState + '<br />status=' + this.status + '<br />responseText=' + this.responseText;
document.getElementById("output").innerHTML = debug;
}
};
xhttp.open("GET", filePath, true);
xhttp.send();
}
test.html (url):
<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">
<head>
<script src="loadfile.js"></script>
</head>
<body onload="loadFile('counter.txt')">
<h1>XMLHttpRequest Test</h1>
<div id='output'></div>
</body>
</html>
输出总是:
XMLHttpRequest Test
readyState=4
status=0
responseText=
有什么我错过的吗?
[编辑 - 2018 年 7 月 12 日,20:07]
curl -I https://downloads.solydxk.com/.counters/counter.txt
返回这个:
HTTP/1.1 200 OK
Server: nginx
Date: Thu, 12 Jul 2018 18:04:06 GMT
Content-Type: text/plain
Content-Length: 5
Last-Modified: Thu, 12 Jul 2018 12:27:35 GMT
Connection: keep-alive
ETag: "5b474937-5"
Referrer-Policy: strict-origin-when-cross-origin
Strict-Transport-Security: max-age=31536000 ; always
x-xss-protection: 1; mode=block
X-Content-Type-Options: nosniff
X-Frame-Options: SAMEORIGIN
Content-Security-Policy: default-src 'none'; script-src 'self' 'unsafe-inline'; img-src 'self'; style-src 'none'; font-src 'none'; frame-src 'none'; frame-ancestors 'none'; connect-src 'none'; object-src 'none'; media-src 'none'; form-action 'none'; base-uri downloads.solydxk.com www.downloads.solydxk.com
X-Powered-By: PleskLin
Accept-Ranges: bytes
[解决方案]
在 Content-Security-Policy 部分中,您会看到 connect-src 设置为“none”。当您能够更改服务器上的 Apache 设置时,请检查您的域的标头是否配置正确。
就我而言,我必须将 connect-src 设置为 'self'。
当您使用 Plesk 维护您的服务器时: 网站与域 > 您的域 > Apache 和 nginx 设置 > 附加标题 > 输入自定义值:
Content-Security-Policy: default-src 'none'; script-src 'self' 'unsafe-inline'; img-src 'self'; style-src 'none'; font-src 'none'; frame-src 'none'; frame-ancestors 'none'; connect-src 'self'; object-src 'none'; media-src 'none'; form-action 'none'; base-uri $host www.$host
【问题讨论】:
-
你在“服务”
counter.txt吗?访问它的网址是什么?
标签: javascript ajax xmlhttprequest