使用react-router,官方推薦用browserhistory,美觀簡潔。但是nginx服務器端的配置也讓人頭疼。
首先看官方舉例的方法:
server { location / { try_files $uri /index.html } }
這個做法問題在於,你必須把你的react應用放到根路徑下,且這個nginx只為這個一個應用服務。這樣是不是有點浪費資源了?
假如我路徑是 www.xxx.com.cn/h5/v1/getView,按照官方的nginx配置,那么就得這么寫
server { location / { root /home/h5/v1; try_files $uri $uri/ /index.html; }
}
這樣配置沒問題,但是你如果想再這個nginx部署其他的web應用,那么目錄路徑問題就讓人尷尬了。
下面有另外一種方式:
server { location /h5 { root /home; try_files $uri $uri/ /h5/v1/index.html; } }
這里的try_files配置值有3項,我們只需要關注最后一項,也就是說,在www.xxx.com.cn/h5/v1/getView訪問這個請求的時候,
會到nginx服務器上,最后會查到 /home 跟 / h5/v1/index.html這個兩個路徑拼接后的所在的資源。
這么寫了后,頁面就不會報404的錯誤了。如果頁面還是空白,說明在你react-router路由寫的有問題。
問題代碼如下:
1 const RouterComponents = () => ( 2 <Switch> 3 <Route exact path='/' component={App} /> 4 <Route path="/getView" component={getView}/> 5 </Switch> 6 )
正確的代碼應該是 寫完整路徑,類似下面的:
1 const RouterComponents = () => ( 2 <Switch> 3 <Route exact path='/' component={App} /> 4 <Route path="/h5/v1/modifypassword" component={getView}/> 5 </Switch> 6 )
最后,上述代碼很不美觀,你可以考慮用react-router4 的basename 屬性,以及ES6的模板字符串 來拼接,怎么美觀怎么處理。
var react-router-prefix = '/h5/v1/'; <Router path=`${react-router-prefix}getView`/>