1. 程式人生 > >【轉】React、Vue直接訪問url地址,訪問出錯報404

【轉】React、Vue直接訪問url地址,訪問出錯報404

直接 .so 開發 跳轉 otf dcom outer ons tac

部署完成後,訪問沒問題,從頁面中點擊跳轉也沒問題,但是只要點擊刷新或通過瀏覽器地址欄回車,就會出現404現象!在本地開發中是沒有這個問題的,調試的時候一切都是正常的

直接訪問地址,便會出現404

http://www.xxx.com/home/application/list

問題原因:

刷新頁面時訪問的資源在服務端找不到,因為vue-router設置的路徑不是真實存在的路徑。

如上的404現象,是因為在nginx配置的根目錄/html/dist下面壓根沒有/home/application/list這個真實資源存在,這些訪問資源都是在js裏渲染的。

問題解決:

後端配置例子

Apache 取消下面註釋

LoadModule rewrite_module modules/mod_rewrite.so

.htaccess添加

<IfModule mod_rewrite.c>
  RewriteEngine On
  RewriteBase /
  RewriteRule ^index\.html$ - [L]
  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteCond %{REQUEST_FILENAME} !-d
  RewriteRule . /index.html [L]
</IfModule>

nginx

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

註意:

因為這麽做以後,你的服務器就不再返回 404 錯誤頁面,因為對於所有路徑都會返回 index.html 文件。為了避免這種情況,你應該在應用最後一個路由給出一個 404 頁面。

const router = new VueRouter({
  mode: history,
  routes: [
    { path: *, component: NotFoundComponent }
  ]
})

最後:直接把模式設定history刪除,用router默認的hash模式,這樣基本上直接訪問url是沒有問題的, 只不過url中會多出一個#號

【轉】React、Vue直接訪問url地址,訪問出錯報404