我一定是在使用旧的google搜索,因为如果您使用javascript的fetch,而不是旧的XMLHttpRequest,我就找不到关于如何执行此操作的线程。
我正在试着测试我的VM是否在线。VM的其余部分被锁定,但我留下了一个开放的端点进行测试。
我尝试使用status来检查服务器是否已启动,但给出了一个与响应错误不同的错误:
fetch("https://rockosmodernserver.westus2.cloudapp.azure.com/ ", {
method: "GET",
}).then(response => response)
.then(data => {
if (data.status == 200){
console.log("server is up")
}
else{
console.log("server is down!!")
}
})如果服务器打开,它就能工作,但是如果服务器关闭,我得到:
VM739:1 GET https://rockosmodernserver.westus2.cloudapp.azure.com/ net::ERR_CONNECTION_REFUSED当我尝试搜索这个时,我得到了XMLHttpRequest的解决方案,但没有为提取模块找到解决方案。
发布于 2022-03-30 17:22:45
你在找渔获物。在catch块中,您可以获取错误。下面的示例您可以访问error对象。
fetch("https://rockosmodernserver.westus2.cloudapp.azure.com/ ", {
method: "GET",
}).then(response => response)
.then(data => {
console.log("server is up")
})
.catch((error) => {
console.error('Error:', error);
console.log("server is down!!")
});
发布于 2022-03-30 17:19:52
如果服务器没有响应,fetch将其作为connection failure并在catch()块中处理。fetch只在连接成功时执行then()块。如果连接未成功,则将执行catch()块。
fetch('something')
.then( response => {})
.catch(error => {
// handle error here
})发布于 2022-03-30 17:23:18
如果服务器不接,他就不能给你答复。这意味着没有状态代码。
更新:当遇到网络错误或服务器端的CORS配置错误时,()承诺将拒绝TypeError,尽管这通常意味着权限问题或类似的问题-例如,404并不构成网络错误。对成功的fetch()的准确检查将包括检查承诺是否已解决,然后检查Response.ok属性的值是否为true。代码应该如下所示:
fetch('flowers.jpg')
.then(response => {
if (!response.ok) {
throw new Error('Network response was not OK');
}
return response.blob();
})
.then(myBlob => {
myImage.src = URL.createObjectURL(myBlob);
})
.catch(error => {
console.error('There has been a problem with your fetch operation:', error);
});第一次编辑:通过使用超时并跟踪超时的发生,这个解决方案可能会有所帮助。https://stackoverflow.com/a/50101022/13111978
https://stackoverflow.com/questions/71681442
复制相似问题