1. 程式人生 > 其它 >nodejs 解決 vue,react history 模式,重新整理404問題

nodejs 解決 vue,react history 模式,重新整理404問題

首先我們要明白一點,history 模式為什麼重新整理會404

1、vue,react :history模式是採用瀏覽器的歷史記錄,瀏覽器視窗有一個history物件,用來儲存瀏覽歷史

2、history渲染頁面:當我們使用後端渲染頁面: /build/index.html 時

(1)例如:nodejs 渲染 index.html, 直接使用開放靜態資源 app.use('/',express.static(path.join(__dirname,'build'))) ,這樣預設 “/” 路徑即可訪問 index.html 頁面

(2)但是當我們路由跳轉時,從路由“/” 跳轉到 “list”時,這時重新整理頁面 “/list” 就不會渲染 index.html 頁面了,因為路徑改變了,就不會渲染index.html 了

3、hash渲染頁面:當我們使用後端渲染頁面: /build/index.html 時,因為使用的hash 模式路徑並不會改變,會由路由 “/#/” 跳轉到 “/#/list”,注意這裡只是改變的hash值,後端並不讀取hash值,所以還是根據路由 “/” 進行渲染 index.html

解決 vue,react history 模式

1、(Express 框架 官方推薦)使用第三方庫 connect-history-api-fallback

(1)安裝connect-history-api-fallback

npm install connect-history-api-fallback --save

(2)在app.js檔案中使用

const history = require('connect-history-api-fallback')
app.use('/', history());

(3)history() 傳入引數覆蓋預設的索引檔案(我們知道express.static 靜態資源預設索引檔案為index.html)

history({
  index: '/default.html'
});

(4)history() 傳入引數,根據url匹配 regex 模式時,重寫索引。可以重寫為靜態字串,也可以使用函式轉換傳入請求

history({
  rewrites: [
    { from: 
/\/soccer/, to: '/soccer.html'} ] });

2、使用 app.all('*') 監聽所以請求 注意:一定寫到所有後端介面路由最後面 !!!前臺頁面路由,不能和後端介面路由重複,不然會響應介面資料

// 處理vue專案路由 history 模式問題 !!! 注意:一定寫到所有後端介面路由最後面(前臺頁面路由,不能和後端介面路由重複 )
app.all('*',(req, res, next)=>{
  res.set({
    'Content-Type': 'text/html; charset=utf-8'
  })
  res.sendFile(path.join(__dirname, '/build/index.html'));
})