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

前端 未结 30 2631
时光取名叫无心
时光取名叫无心 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:38

    Try adding ".htaccess" file inside the public folder with the below code.

    RewriteEngine On
    RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI} -f [OR]
    RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI} -d
    RewriteRule ^ - [L]
    
    RewriteRule ^ /index.html [L]  
    
    0 讨论(0)
  • 2020-11-21 05:38

    This topic is a little bit old and solved but I would like to suggest you a simply, clear and better solution. It works if you use web server.

    Each web server has an ability to redirect the user to an error page in case of http 404. To solve this issue you need to redirect user to the index page.

    If you use Java base server (tomcat or any java application server) the solution could be the following:

    web.xml:

    <?xml version="1.0" encoding="UTF-8"?>
    <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
             version="3.1">
    
        <!-- WELCOME FILE LIST -->
        <welcome-file-list>
            <welcome-file>index.jsp</welcome-file>
        </welcome-file-list>
    
        <!-- ERROR PAGES DEFINITION -->
        <error-page>
            <error-code>404</error-code>
            <location>/index.jsp</location>
        </error-page>
    
    </web-app>
    

    Example:

    • GET http://example.com/about
    • Web server throws http 404 because this page does not exist on the server side
    • the error page configuration tells to the server that send the index.jsp page back to the user
    • then JS will do the rest of the job on the clien side because the url on the client side is still http://example.com/about.

    That is it, no more magic needs:)

    0 讨论(0)
  • 2020-11-21 05:38

    If you are using Express or some other framework in the backend , you can add the similar configuration as below and check out the Webpack public path in the configuration, it should work fine even on reload if you are using BrowserRouter

    expressApp.get('/*', (request, response) => {
        response.sendFile(path.join(__dirname, '../public/index.html'));
    });
    
    0 讨论(0)
  • 2020-11-21 05:39

    If you're hosting a react app via AWS Static S3 Hosting & CloudFront

    This problem presented itself by CloudFront responding with a 403 Access Denied message because it expected /some/other/path to exist in my S3 folder, but that path only exists internally in React's routing with react-router.

    The solution was to set up a distribution Error Pages rule. Go to the CloudFront settings and choose your distribution. Next go to the "Error Pages" tab. Click "Create Custom Error Response" and add an entry for 403 since that's the error status code we get. Set the Response Page Path to /index.html and the status code to 200. The end result astonishes me with its simplicity. The index page is served, but the URL is preserved in the browser, so once the react app loads, it detects the URL path and navigates to the desired route.

    Error Pages 403 Rule

    0 讨论(0)
  • 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

    <Router history={hashHistory} >
       <Route path="/home" component={Home} />
       <Route path="/aboutus" component={AboutUs} />
    </Router>
    

    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.

    <VirtualHost *:80>
        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
        <Directory "/var/www/html/">
                Options Indexes FollowSymLinks
                AllowOverride all
                Require all granted
        </Directory>
    </VirtualHost>
    

    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.

    0 讨论(0)
  • 2020-11-21 05:39

    If you're using firebase all you have to do is make sure you've got a rewrites property in your firebase.json file in the root of your app (in the hosting section).

    For example:

    { 
      "hosting": {
        "rewrites": [{
          "source":"**",
          "destination": "/index.html"
        }]    
      }
    }
    

    Hope this saves somebody else a hoard of frustration and wasted time.

    Happy coding...

    Further reading on the subject:

    https://firebase.google.com/docs/hosting/full-config#rewrites

    Firebase CLI: "Configure as a single-page app (rewrite all urls to /index.html)"

    0 讨论(0)
提交回复
热议问题