React-router urls don't work when refreshing or writing manually

前端 未结 30 2643
时光取名叫无心
时光取名叫无心 2020-11-21 05:07

I\'m using React-router and it works fine while I\'m clicking on link buttons, but when I refresh my webpage it does not load what I want.

For instance, I am in

30条回答
  •  误落风尘
    2020-11-21 05:39

    This can solve your problem

    I also faced the same problem in the ReactJS application in Production mode. Here is the 2 solution to the problem.

    1.Change the routing history to "hashHistory" instead of browserHistory in the place of

    
       
       
    
    

    Now build the app using the command

    sudo npm run build
    

    Then place the build folder in your var/www/ folder, Now the application is working fine with the addition of # tag in each and every URL. like

    localhost/#/home localhost/#/aboutus

    Solution 2: Without # tag using browserHistory,

    Set your history = {browserHistory} in your Router, Now build it using sudo npm run build.

    You need to create the "conf" file to solve the 404 not found page, the conf file should be like this.

    open your terminal type the below commands

    cd /etc/apache2/sites-available ls nano sample.conf Add the below content in it.

    
        ServerAdmin admin@0.0.0.0
        ServerName 0.0.0.0
        ServerAlias 0.0.0.0
        DocumentRoot /var/www/html/
    
        ErrorLog ${APACHE_LOG_DIR}/error.log
        CustomLog ${APACHE_LOG_DIR}/access.log combined
        
                Options Indexes FollowSymLinks
                AllowOverride all
                Require all granted
        
    
    

    Now you need to enable the sample.conf file by using the following command

    cd /etc/apache2/sites-available
    sudo a2ensite sample.conf
    

    then it will ask you to reload the apache server, using sudo service apache2 reload or restart

    then open your localhost/build folder and add the .htaccess file with the content of below.

       RewriteEngine On
       RewriteBase /
       RewriteCond %{REQUEST_FILENAME} !-f
       RewriteCond %{REQUEST_FILENAME} !-d
       RewriteCond %{REQUEST_FILENAME} !-l
       RewriteRule ^.*$ / [L,QSA]
    

    Now the app is working normally.

    Note: change 0.0.0.0 IP to your local IP address.

    If any doubts regarding this feel free to raise a comment.

    I hope it is helpful to others.

提交回复
热议问题