【问题标题】:How can I configure Vite's dev server to give 404 errors?如何配置 Vite 的开发服务器以给出 404 错误?
【发布时间】:2021-12-10 13:34:57
【问题描述】:

使用 Vite 的开发服务器,如果我尝试访问一个不存在的 URL(例如 localhost:3000/nonexistent/index.html),我会收到 404 错误。相反,我收到了一个200 状态码,以及localhost:3000/index.html 的内容。

如何配置 Vite 以在这种情况下返回 404

(这个问题:Serve a 404 page with app created with Vue-CLI,非常相似,但与基于 Webpack 的 Vue-CLI 而不是 Vite 相关。)

【问题讨论】:

    标签: vue.js http-status-code-404 vite devserver


    【解决方案1】:

    Vite 2.6.11 不支持禁用历史 API 回退,尽管有一个开放的拉取请求引入了可用于禁用历史回退中间件 (vitejs/vite#4640) 的配置。

    作为一种解决方法,您可以添加一个custom plugin,它可以有效地禁用历史 API 回退。 Vite 的插件 API 包括 configureServer() hook,它允许将自定义中间件添加到底层 connect 实例。您可以添加一个中间件,为未找到的 URL 请求发送 404 状态代码。

    这是编写该插件的一种方法:

    // vite.config.js
    import { defineConfig } from 'vite'
    import vue from '@vitejs/plugin-vue'
    
    function disableHistoryFallback() {
      const path = require('path')
      const fs = require('fs')
    
      const ALLOWLIST = [
        // internal requests
        /^\/__vite_ping/,
        /^\/@vite\/client/,
        /^\/@id/,
        /^\/__open-in-editor/,
    
        // no check needed
        /^\/$/,
        /^\/index.html/,
      ]
      return {
        name: 'disable-history-fallback',
        configureServer(server) {
          server.middlewares.use((req, res, next) => {
            // remove query params from url (e.g., cache busts)
            const url = req.url.split('?')[0]
    
            if (ALLOWLIST.some(pattern => pattern.test(url))) {
              return next()
            }
    
            if (!fs.existsSync(path.join(__dirname, url))) {
              console.warn('URL not found:', url)
              res.statusCode = 404
              res.end()
            } else {
              next()
            }
          })
        }
      }
    }
    
    export default defineConfig({
      plugins: [vue(), disableHistoryFallback()],
    })
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-01-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-06-07
      • 1970-01-01
      • 2013-08-28
      相关资源
      最近更新 更多