js实现404
在JavaScript中实现404页面处理
通过监听路由变化或检查资源状态,可以动态触发404页面的显示或跳转。以下是几种常见实现方式:
使用前端路由库(如React Router)
在单页应用(SPA)中,可以通过路由配置定义404页面:
// React Router v6示例
import { Routes, Route } from 'react-router-dom';
function App() {
return (
<Routes>
<Route path="/" element={<Home />} />
<Route path="/about" element={<About />} />
<Route path="*" element={<NotFound />} /> // 匹配所有未定义路径
</Routes>
);
}
原生JavaScript检测无效路径
通过解析当前URL路径与有效路由列表对比:
const validRoutes = ['/', '/home', '/contact'];
const currentPath = window.location.pathname;
if (!validRoutes.includes(currentPath)) {
window.location.href = '/404.html'; // 跳转至静态404页面
// 或动态渲染404内容
document.body.innerHTML = '<h1>404 Not Found</h1>';
}
动态内容加载失败处理
当异步加载资源失败时触发404状态:
fetch('/api/data')
.then(response => {
if (response.status === 404) {
throw new Error('Resource not found');
}
return response.json();
})
.catch(error => {
if (error.message.includes('404')) {
render404Page();
}
});
function render404Page() {
// 动态插入404内容
}
服务端配合方案
结合Node.js等后端服务返回404状态码:
// Express示例
app.use((req, res, next) => {
res.status(404).sendFile(path.join(__dirname, '404.html'));
});
前端可通过检查响应状态码处理:
fetch('/some-page')
.then(res => {
if (res.status === 404) {
// 处理404逻辑
}
});
注意事项
- 对于SEO优化,确保服务端返回真实的HTTP 404状态码
- 在静态网站中,需配置服务器(如Nginx)将所有未匹配路径指向404页面
- 提供返回首页或导航选项改善用户体验
- 考虑记录404路径用于分析无效链接







