2

Vue history 模式下路由刷新 404

 1 year ago
source link: https://5ime.cn/vue-route-404.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
Vue history 模式下路由刷新 404

Vue history 模式下路由刷新 404

今天在用 vue 重写 I Am I の 实验室 的时候,发现了一个问题,vue-router 的默认路由是 hash 模式,也就是说,默认路由的路径是这样的

url/#/path

我改为了 history 模式,路由的路径是这样的

url/path

改过之后一切正常,但是当我上传到服务器之后,第一次切换页面,路由是正常的,但是当我刷新页面的时候,服务器没有获取到对应的路由,出现了 404

这个问题解决起来也很简单,最近重构 TenAPI 也是遇到类似的问题,通过编写伪静态规则解决。

当服务器收到请求的时候,就返回 index.html,然后让我们自定义的路由去处理,这里我使用的是 nginx,配置如下

location / {
try_files $uri $uri/ /index.html;
}

我把这个项目放到了 Github 上,通过 Github Actions 自动部署到 Vercel 上,所以我们重新定义 Vercel 的规则。

直接在 public 目录下新建一个 vercel.json,然后把下面的内容复制过去,就可以了。

{
"rewrites": [{ "source": "/:path*", "destination": "/index.html" }]
}

其次就是为什么本地不会出现这个问题,最后发现是因为 vue-cliwebpack 配置中默认开启了 historyApiFallback

我们可以在 @vue\cli-service\lib\commands\serve.js 中找到这个配置,当我们访问一个不存在的路由的时候,会返回 index.html,然后让前端的路由去处理。

historyApiFallback: {
disableDotRule: true,
htmlAcceptHeaders: [
'text/html',
'application/xhtml+xml'
],
rewrites: genHistoryApiFallbackRewrites(baseUrl, options.pages)
},

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK