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

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

    Production stack: React, React Router v4, BrowswerRouter, Express, Nginx

    1) User BrowserRouter for pretty urls

    // app.js
    
    import { BrowserRouter as Router } from 'react-router-dom'
    
    const App = () {
      render() {
        return (
            
               // your routes here
            
        )
      }
    }
    

    2) Add index.html to all unknown requests by using /*

    // server.js
    
    app.get('/*', function(req, res) {   
      res.sendFile(path.join(__dirname, 'path/to/your/index.html'), function(err) {
        if (err) {
          res.status(500).send(err)
        }
      })
    })
    

    3) bundle webpack with webpack -p

    4) run nodemon server.js or node server.js

    EDIT: You may want to let nginx handle this in the server block and disregard step 2:

    location / {
        try_files $uri /index.html;
    }
    

提交回复
热议问题