React routing not working while manually changing URL | React-router 4

后端 未结 3 1751
慢半拍i
慢半拍i 2021-01-23 01:56

My Routing is working perfectly when URL is changed through Link component of React-router. However, if I try to change URL manually in browser, it hits 404 Error.

Below

相关标签:
3条回答
  • 2021-01-23 02:10

    When using BrowserRouter , you need to add historApiFallback: true in your webpack.

    Add this to your webpack config

    devServer: {
        historyApiFallback: true,
      },
    

    The gulp equivalent would be something like:

    historyApiFallback = require('connect-history-api-fallback')
    
    
    //start a local dev server
    gulp.task('connect', function() {
      connect.server({
        root: ['dist'],
        port: config.port,
        base: config.devBaseUrl,
        livereload: true,
        middleware: [ historyApiFallback() ]
      });
    });
    

    See this link for more details

    0 讨论(0)
  • 2021-01-23 02:14

    if you are using webpack-dev-server. set:

    devServer{
      //...
      historyApiFallback: true
    }
    

    it would serve 'index.html' in place of any 404 responses...

    if you've published to server.make sure your server config make it redirect to main html

    express:

    app.get('/*', function(req, res) {
        res.sendfile('index.html');
    });
    

    gulp-connect:

    connect.server({
      root: ['dist'],
      port: config.port,
      base: config.devBaseUrl,
      livereload: true,
      fallback: 'index.html'
    });
    
    0 讨论(0)
  • 2021-01-23 02:17

    This worked for me:

      var historyApiFallback = require('connect-history-api-fallback');
    
      gulp.task('connect', function() {
        connect.server({
          root: ['dist'],
          port: config.port,
          base: config.devBaseUrl,
          livereload: true,
          middleware: function(connect, opt) {
            return [
              historyApiFallback({})
            ]
          }
        });
      });
    

    Thanks to @Shubham Khatri and @LinJI for all the help !

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