在JavaScript中,处理HTTP 404错误通常涉及到网络请求,例如使用fetch
API或XMLHttpRequest
来从服务器获取资源。当服务器返回404状态码时,表示请求的资源不存在。以下是如何处理这种情况的步骤:
使用fetch
API的示例代码如下:
fetch('https://api.example.com/data')
.then(response => {
if (!response.ok) {
if (response.status === 404) {
// 处理404错误
console.error('资源未找到');
} else {
// 处理其他HTTP错误
console.error(`HTTP错误! 状态: ${response.status}`);
}
return; // 终止后续的.then()链
}
return response.json(); // 解析JSON数据
})
.then(data => {
// 使用数据进行操作
console.log(data);
})
.catch(error => {
// 处理网络请求失败的情况
console.error('网络请求失败:', error);
});
使用XMLHttpRequest
的示例代码如下:
var xhr = new XMLHttpRequest();
xhr.open('GET', 'https://api.example.com/data', true);
xhr.onreadystatechange = function() {
if (xhr.readyState === XMLHttpRequest.DONE) {
if (xhr.status === 200) {
// 请求成功,处理数据
var data = JSON.parse(xhr.responseText);
console.log(data);
} else if (xhr.status === 404) {
// 处理404错误
console.error('资源未找到');
} else {
// 处理其他HTTP错误
console.error(`HTTP错误! 状态: ${xhr.status}`);
}
}
};
xhr.onerror = function() {
// 处理网络请求失败的情况
console.error('网络请求失败');
};
xhr.send();
在这两个示例中,我们都检查了响应的状态码,并在检测到404状态码时执行了错误处理逻辑。这可以包括显示用户友好的消息、记录错误或执行其他恢复操作。