周玲安多大,王伶儿,wow幸运卡片
问题背景:
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/上就可以了。
解决方案:
对于vue的router[mode: history]模式在开发的时候,一般都不出问题。是因为开发时用的服务器为node,dev环境中自然已配置好了。
但对于放到nginx下运行的时候,自然还会有其他注意的地方。总结如下:
在nginx里配置了以下配置后, 可能首页没有问题,但链接其他会出现(404)
location / { root d:\test\exprice\dist; index index.htm; try_files $uri $uri/ /; 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:\test\exprice\dist; index index.htm; try_files $uri $uri/ /;
2、匹配errpr_page
location /{ root /data/nginx/html; index index.htm; error_page 404 /; }
3、 (vue.js官方教程里提到的)
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.htm; } #对应上面的@router,主要原因是路由的路径资源并不是一个真实的路径,所以无法找到具体的文件 #因此需要rewrite到中,然后交给路由在处理请求资源 location @router { rewrite ^.*$ / last; } #.......其他部分省略 }
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。
如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复
VUE+elementui组件在table-cell单元格中绘制微型echarts图
Vue通过getAction的finally来最大程度避免影响主数据呈现问题
vue 路由懒加载中给 Webpack Chunks 命名的方法
网友评论