首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何将Vite的开发服务器配置为提供404错误?

如何将Vite的开发服务器配置为提供404错误?
EN

Stack Overflow用户
提问于 2021-10-25 00:22:04
回答 1查看 547关注 0票数 2

使用Vite的开发服务器,如果我试图访问一个不存在的网址(例如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相关。)

EN

回答 1

Stack Overflow用户

发布于 2021-10-25 16:56:41

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

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

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

代码语言:javascript
复制
// 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()],
})
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/69701743

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档