简体   繁体   中英

How to fix page refresh issues in reactjs

When I hit F5 / refresh the webpage I get a 404 not found error on my react app hosted by apache 2.2

I am running reactjs with react boot strap and routes

I have seen online ppl have added a .htaccess file in the public folder and then built the app but this has not worked for me

import './App.css';
import { BrowserRouter as Router,
        Route,
        Link,
        Switch,
        Redirect
 } from 'react-router-dom';
import Home from './components/Home';
import Test from './components/Test';
import Test1 from './components/Test1';


class App extends Component {
  render() {
    return (
      <Router>
        <div>
          <Navbar />
        <Switch>
          <Route exact path="/" component={Home} />
          <Route exact path="/home" component={Home} />
          <Route exact path="/test" component={Test} />
          <Route exact path="/test1" component={Test1} />
          <Route component={NoMatch} />
        </Switch>
        </div>
      </Router>
    );
  }
}

export default App;

I suppose that you do the refresh when you're not in the root.

I use this .htaccess file for my app to make the routes work properly

RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.html [L]

We had this issue and we used the following setup:

<VirtualHost *:8080>
  ServerName example.com
  DocumentRoot /var/www/httpd/example.com

  <Directory "/var/www/httpd/example.com">
    ...

    RewriteEngine on
    # Don't rewrite files or directories
    RewriteCond %{REQUEST_FILENAME} -f [OR]
    RewriteCond %{REQUEST_FILENAME} -d
    RewriteRule ^ - [L]
    # Rewrite everything else to index.html to allow html5 state links
    RewriteRule ^ index.html [L]
  </Directory>
</VirtualHost>

We got this configuration from here .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM