react項目運用BrowserRouter上線後在非根路由情況下刷新出現404問題的解決方法 -- Koa

問題

先上react App代碼

class App extends React.Component {
  render() {
    return (
      <BrowserRouter>
        <div>
          <Link to="/lottery">to lottery</Link>
          <Route path="/lottery" component={Lottery} exact />
          <Route path="/a" render={() => <div>in a</div>} exact />
        </div>
      </BrowserRouter>      
    )
  }
}

clipboard.png

點擊後可以正常跳轉至lottery路由,忽略醜陋的界面...

clipboard.png

這時刷新就404找不到頁面了

clipboard.png

原因

react的BrowserRouter用的是Html5提供的HistoryApi方法,Link組件實際上是調用了History.pushState(),然後通過監聽history狀態去展示或者隱藏組件。所以當刷新時,也就是向服務器發送了這個路徑的請求,而服務器上實際是沒有對這個路徑的請求做任何處理的,故返回的是404。

解決方法 -- 用的是koa搭建服務器

app.use(views(path.resolve(__dirname, '../www/dist'), {extension: 'html'}))
app.use(async (ctx, next) => {
  console.log(ctx.path)
  await next()
})

app.use(router.routes())
router.all(/\.js/i, static(path.resolve(__dirname, '../www/dist')))
router.all('*', async ctx => {
  await ctx.render('index')
})

只要不是以.js結束的路由請求都返回index.html,js類型的就從項目打包出來的靜態資源裏找,相當於把路由的控制權交給了前端。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章