vue页面访问正常,但是一刷新就会404的问题?
为什么会出现404?
我们打开dist文件夹,可以看到只有一个 index.html 文件及一些静态资源,这个是因为Vue是单页应用(SPA),只有一个index.html作为入口文件,其它的路由都是通过JS来进行跳转;
接着我们再来分析一下后端 nginx 的配置.
我们现在可以根据 nginx 配置得出,当我们在地址栏输入 website.com 时,这时会打开我们 dist 目录下的 index.html 文件,然后我们在跳转路由进入到 website.com/login;
关键在这里,当我们在 website.com/login 页执行刷新操作,nginx location 是没有相关配置的,所以就会出现 404 的情况.
解决办法
第一种解决方法
将vue路由模式mode: 'history' 修改为 mode: 'hash'
为什么hash模式下没有问题?
router hash 模式我们都知道是用符号#表示的,如 website.com/#/login, hash 的值为 #/login;
它的特点在于:hash 虽然出现在 URL 中,但不会被包括在 HTTP 请求中,对服务端完全没有影响,因此改变 hash 不会重新加载页面;
hash 模式下,仅 hash 符号之前的内容会被包含在请求中,如 website.com/#/login 只有 website.com 会被包含在请求中 ,因此对于服务端来说,即使没有配置location,也不会返回404错误.
第二种解决方法
在服务器Nginx配置文件里,添加如下代码,再重启Nginx,刷新网页就OK了
箴言:因为这些东西是非常简单的。不要抱怨自己学不会,那是因为你没有足够用心。