使用 vue3 路由重新加载页面时出现 404 错误
Error 404 on page reload with vue3 routing
问题
当我在 vue3.js 中的路径(例如 /installer)上点击重新加载时,出现以下错误:
代码
我使用具有以下设置的 Router:
const router = createRouter({
history: createWebHistory(process.env.BASE_URL),
routes,
});
附加信息
(我不使用 createWebHashHistory 来删除 url 中的主题标签)
我去路线时也遇到这个错误,例如/installer,直接而不是通过 link.
问题
如何解决这个错误?
这与您的服务器配置有关,通读this section from the docs:
... Here comes a problem, though: Since our app is a single page client side app, without a proper server configuration, the users will get a 404 error if they access https://example.com/user/id directly in their browser. Now that's ugly. Not to worry: To fix the issue, all you need to do is add a simple catch-all fallback route to your server. If the URL doesn't match any static assets, it should serve the same index.html page that your app lives in. Beautiful, again!
The section below it针对不同的服务器给出了不同的示例。
它建议对 Express 服务器使用 connect-history-api-fallback 包,但我一直只使用它,效果很好:
if (process.env.NODE_ENV === 'production') {
// Handle SPA
app.get(/.*/, (req, res) => res.sendFile(__dirname + '/public/index.html'));
}
如果您使用的是 nginx,我建议将此行添加到 nginx 配置文件中:
location / {
try_files $uri $uri/ /index.html;
}
参考:https://next.router.vuejs.org/guide/essentials/history-mode.html#apache
问题
当我在 vue3.js 中的路径(例如 /installer)上点击重新加载时,出现以下错误:
代码
我使用具有以下设置的 Router:
const router = createRouter({
history: createWebHistory(process.env.BASE_URL),
routes,
});
附加信息
(我不使用 createWebHashHistory 来删除 url 中的主题标签)
我去路线时也遇到这个错误,例如/installer,直接而不是通过 link.
问题
如何解决这个错误?
这与您的服务器配置有关,通读this section from the docs:
... Here comes a problem, though: Since our app is a single page client side app, without a proper server configuration, the users will get a 404 error if they access https://example.com/user/id directly in their browser. Now that's ugly. Not to worry: To fix the issue, all you need to do is add a simple catch-all fallback route to your server. If the URL doesn't match any static assets, it should serve the same index.html page that your app lives in. Beautiful, again!
The section below it针对不同的服务器给出了不同的示例。
它建议对 Express 服务器使用 connect-history-api-fallback 包,但我一直只使用它,效果很好:
if (process.env.NODE_ENV === 'production') {
// Handle SPA
app.get(/.*/, (req, res) => res.sendFile(__dirname + '/public/index.html'));
}
如果您使用的是 nginx,我建议将此行添加到 nginx 配置文件中:
location / {
try_files $uri $uri/ /index.html;
}
参考:https://next.router.vuejs.org/guide/essentials/history-mode.html#apache