我是一个完全的Javascript初学者。我正试图用以下代码轮询一个JSON状态页:
setInterval(refresh, 5000);
var beat_state = 0;
function refresh()
{
fetch("http://localhost:8080/", {headers: {"Accept": "application/json"}, mode: 'no-cors'}).then(
function(response) {
if (response.ok) {
document.getElementById("hearth").textContent = "❤️";
response.json().then(update_display);
} else {
document.getElementById("hearth").textContent = "💔️";
}
}
);
}
function update_display(json_health)
{
/* ... */
}
服务器返回此响应:
HTTP/1.1 200 OK
Content-Type: application/json
Content-Length: 186
Date: Sun, 06 Sep 2020 20:25:59 GMT
Server: lighttpd/1.4.55
{"socket_listening": true,"quick_shutdown": false,"workers_online": 20,"workers_sleeping": 19,"workers_backlog": 0,"connections": [{"id": 4,"active_requests": 1,"socket_insane": false}]}
我正在用一个独立的磁盘HTML页面进行测试。假设Firefox 80.0.1控制台显示请求成功且没有错误。为什么reponse.ok
为false?
当您有模式时:'no-cors'
您将得到类型为"的响应;不透明的";
返回状态:0
由于ok仅在200-299范围内的状态下为true,因此您可以得到ok:false
来源:
OK状态
是什么类型的不透明
无cors 的不透明响应
我会尝试更改fetch语法,看起来你已经做了一些嵌套的"。那么";s、 这可能会导致提取不起作用为了让流程运行并捕捉错误,也许像这样的东西可以在中工作
setInterval(refresh, 5000);
var beat_state = 0;
function refresh()
{
fetch("http://localhost:8080/", {headers: {"Accept": "application/json"}, mode: 'no-cors'})
.then(function(response) { if (response.ok) {
document.getElementById("hearth").textContent = "❤️";
return response.json();
} else {
document.getElementById("hearth").textContent = "💔️";
}
})
.then(function(json) {
update_display();
}
.catch(error => {
console.log(error.message);
})