zoukankan      html  css  js  c++  java
  • 解决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`/>
  • 相关阅读:
    xml=>数组
    php的session锁
    压缩服务器中的文件夹,并下载到电脑
    通过onkeydown事件来控制只允许数字
    简单算法
    memcahe安装
    HTML div css 强制 换行 不换行
    windows charles response 乱码解决办法
    根据字节流判断内容是否使用UTF-8编码
    nginx安装过程
  • 原文地址:https://www.cnblogs.com/ldld/p/8483772.html
Copyright © 2011-2022 走看看