uni-app 在 vue3+uniapp+vite 使用 history 模式时无法直接访问除根目录外的其他页面或刷新出现空白页?
uni-app 在 vue3+uniapp+vite 使用 history 模式时无法直接访问除根目录外的其他页面或刷新出现空白页?
示例代码:
"h5": {
"devServer": {
"port": 8080
},
"router": {
"mode": "history",
"base": "./"
}
}
操作步骤:
- 打开根目录->跳转到其他页面->刷新页面则是空白
- 直接访问非根目录页面打开白屏
预期结果:
正常访问
实际结果:
无法访问,出现白屏
bug描述:
- vue3+uniapp+vite使用history模式时H5无法直接访问除开根目录的其他页面或者刷新也是空白页,后端已经配置了,但是还是不行。改成hash模式可以正常访问和使用
- 在本地输入路由可以正常访问,打包线上除开根目录,其他页面无法通过链接直接访问,需要在根目录跳转才可以
| 项目信息 | 详细信息 |
|----------------|------------------|
| 产品分类 | uniapp/H5 |
| PC开发环境 | Windows |
| PC开发环境版本 | 微信开发者工具 stable 1.06.2308310 |
| 浏览器平台 | 微信内置浏览器 |
| 浏览器版本 | 微信开发者工具 stable 1.06.2308310 |
| 项目创建方式 | CLI |
| CLI版本号 | [@vue](/user/vue)/ci 5.0.8 |
更多关于uni-app 在 vue3+uniapp+vite 使用 history 模式时无法直接访问除根目录外的其他页面或刷新出现空白页?的实战教程也可以访问 https://www.itying.com/category-93-b0.html
感谢反馈。你提到 h5 vue3+history 访问路由本地可以,线上打不开,这个一般是 nginx 配置有问题。 你可以搜索 vue history nginx 找到一些解决方案。
更多关于uni-app 在 vue3+uniapp+vite 使用 history 模式时无法直接访问除根目录外的其他页面或刷新出现空白页?的实战教程也可以访问 https://www.itying.com/category-93-b0.html
history 模式下,没有匹配的路由白屏了怎么处理,已经配置好了nginx为无匹配路由时进入/index.html。例如:/pages/my/my 为正确的路由,如果直接访问域名/pages 就会导致白屏,此时已经进入了uniapp程序只是没有路由渲染
希望没有匹配的路由时进入首页
在使用 uni-app + Vue 3 + Vite 开发应用时,如果你配置了 history 模式的路由,可能会遇到直接访问除根目录外的其他页面或刷新页面时出现空白页的问题。这是因为 history 模式的路由依赖于服务器配置来处理 URL 请求,而默认情况下,服务器可能无法正确处理这些请求。
问题原因
在 history 模式下,Vue Router 会使用 pushState API 来管理 URL,而不是通过哈希 (#) 来管理。这意味着当你访问一个非根路径的 URL 时(例如 /about),服务器需要能够正确地返回 index.html,然后由 Vue Router 来处理路由。如果服务器没有正确配置,它可能会返回 404 错误或空白页。
解决方案
1. 服务器配置
你需要确保服务器在接收到任何路径请求时,都返回 index.html 文件。以下是常见的服务器配置示例:
-
Nginx:
location / { try_files $uri $uri/ /index.html; } -
Apache:
<IfModule mod_rewrite.c> RewriteEngine On RewriteBase / RewriteRule ^index\.html$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_NAMEFILENAME} !-d RewriteRule . /index.html [L] </IfModule> -
Express (Node.js):
const express = require('express'); const path = require('path'); const app = express(); app.use(express.static(path.join(__dirname, 'dist'))); app.get('*', (req, res) => { res.sendFile(path.join(__dirname, 'dist', 'index.html')); }); app.listen(3000, () => { console.log('Server is running on http://localhost:3000'); });
2. Vite 配置
在 vite.config.js 中,确保 base 配置正确。通常你可以将 base 设置为 ./,以便在构建时正确处理资源路径。
export default defineConfig({
base: './',
// 其他配置
});
3. 部署到子目录
如果你的应用部署在一个子目录下(例如 /my-app),你需要在 router 和 vite.config.js 中配置 base。
-
Vite 配置:
export default defineConfig({ base: '/my-app/', // 其他配置 }); -
Vue Router 配置:
const router = createRouter({ history: createWebHistory('/my-app/'), routes: [ // 你的路由配置 ], });
4. 开发环境中的问题
在开发环境中,Vite 默认会处理 history 模式的路由请求,但如果你遇到问题,可以尝试以下方法:
- 确保
vite.config.js中的server配置正确:export default defineConfig({ server: { historyApiFallback: true, }, // 其他配置 });

