当前位置:首页 > JavaScript

js实现404

2026-02-02 10:54:14JavaScript

在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路径用于分析无效链接

js实现404

标签: js
分享给朋友:

相关文章

vue.js实现轮播

vue.js实现轮播

Vue.js 实现轮播功能 使用第三方库(推荐) Vue.js 生态中有许多成熟的轮播组件库,例如 vue-awesome-swiper 或 swiper,它们功能丰富且易于集成。 安装 swip…

js实现拖拽

js实现拖拽

实现拖拽的基本步骤 通过监听鼠标事件(mousedown、mousemove、mouseup)实现拖拽功能。以下是核心代码逻辑: const draggableElement = document…

js实现复制

js实现复制

使用document.execCommand方法 在较旧的浏览器中,可以使用document.execCommand('copy')实现复制功能。创建一个临时的textarea或input元素,将需要…

js实现文件下载

js实现文件下载

使用 a 标签下载文件 通过动态创建 a 标签并设置 download 属性实现文件下载。适用于已知文件 URL 或 Blob 数据的情况。 function downloadFile(url,…

js实现图片预览

js实现图片预览

使用FileReader API实现图片预览 通过FileReader对象读取用户选择的图片文件并显示预览: const input = document.getElementById('imag…

js 实现分页

js 实现分页

实现分页的基本逻辑 分页功能通常需要后端返回数据总量或总页数,前端根据当前页码和每页条数截取对应数据。以下是一个基于JavaScript的简单分页实现方案: 前端分页实现 假设已有从后端获取的完整数…