解决react-router4在browserhistory路由下的nginx的白屏或者404问题


  使用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`/>

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM