一聚教程网:一个值得你收藏的教程网站

最新下载

热门教程

VUE的history模式下除了index外其他路由404报错解决办法

时间:2019-08-21 编辑:猪哥 来源:一聚教程网

我们先来看下代码:

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

try_files首先会判断他是文件,还是一个目录,结果发现他是文件,与第一个参数 $uri变量匹配。
然后去到网站目录下去查找文件是否存在,如果存在直接读取返回。如果不存在直接跳转到第三个参数.

现在不明白的是既然跳到了index为什么显示的还是路由后的界面

内容扩展:

问题背景:

vue-router 默认是hash模式,使用url的hash来模拟一个完整的url,当url改变的时候,页面不会重新加载。但是如果我们不想hash这种以#号结尾的路径时候的话,我们可以使用路由的history的模式。比如如下网址:使用hash模式的话,那么访问变成 http://localhost:8080/bank/page/count/#/ 这样的访问,如果路由使用 history的话,那么访问的路径变成 如下:http://localhost:8080/bank/page/count 这样的了;

不过history的这种模式需要后台配置支持。比如:当我们进行项目的主页的时候,一切正常,可以访问,但是当我们刷新页面或者直接访问路径的时候就会返回404,那是因为在history模式下,只是动态的通过js操作window.history来改变浏览器地址栏里的路径,并没有发起http请求,但是当我直接在浏览器里输入这个地址的时候,就一定要对服务器发起http请求,但是这个目标在服务器上又不存在,所以会返回404

怎么解决呢?我们现在可以把所有请求都转发到 http://localhost:8080/bank/page/index.html上就可以了。

解决方案:

对于VUE的router[mode: history]模式在开发的时候,一般都不出问题。是因为开发时用的服务器为node,Dev环境中自然已配置好了。

但对于放到nginx下运行的时候,自然还会有其他注意的地方。总结如下:

在nginx里配置了以下配置后, 可能首页没有问题,但链接其他会出现(404)

    location / {
   root D:Testexpricedist;
   index index.html index.htm;
   try_files $uri $uri/ /index.html;
   add_header 'Access-Control-Allow-Origin' '*';
   add_header 'Access-Control-Allow-Credentials' 'true';
   add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
   add_header 'Access-Control-Allow-Headers' 'DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type';
  }
  
  location ^~/api/ {
   proxy_pass http://39.105.109.245:8080/;
  }

为了解决404,需要通过以下两种方式:

1、官网推荐

location / {
  root D:Testexpricedist;
  index index.html index.htm;
  try_files $uri $uri/ /index.html;

2、匹配errpr_page

location /{
  root /data/nginx/html;
  index index.html index.htm;
  error_page 404 /index.html;
}

3、

 server {
  listen  8888;#默认端口是80,如果端口没被占用可以不用修改
  server_name localhost;
  root  E:/vue/my_project/dist;#vue项目的打包后的dist
  location / {
   try_files $uri $uri/ @router;#需要指向下面的@router否则会出现vue的路由在nginx中刷新出现404
   index index.html index.htm;
  }
  #对应上面的@router,主要原因是路由的路径资源并不是一个真实的路径,所以无法找到具体的文件
  #因此需要rewrite到index.html中,然后交给路由在处理请求资源
  location @router {
   rewrite ^.*$ /index.html last;
  }
  #.......其他部分省略
 }

热门栏目