使用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相关。)
发布于 2021-10-25 16:56:41
Vite 2.6.11不支持禁用历史API回退,尽管有一个开放的拉取请求引入了一个可用于禁用历史回退中间件(vitejs/vite#4640)的配置。
作为一种解决方法,您可以添加一个custom plugin来有效地禁用历史API回退。Vite的插件API包括允许向底层connect实例添加自定义中间件的configureServer() hook。您可以添加一个中间件,为未找到的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()],
})https://stackoverflow.com/questions/69701743
复制相似问题