問題背景:
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:/Test/exprice/dist;      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:/Test/exprice/dist;  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、 (vue.js官方教程里提到的https://router.vuejs.org/zh-cn/essentials/history-mode.html)
 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;    }    #.......其他部分省略 }            
新聞熱點
疑難解答
圖片精選