为什么devserver在刷新页面时会给出404响应?

时间:2017-09-16 18:20:18

标签: javascript reactjs webpack

所以我有一个使用WebPack devServer的React应用程序。如果我在localhost:8080/popular并刷新页面,即使我在app.js中指定当我们在/popular路由时加载Popular组件,我也会收到404错误:

class App extends React.Component {
  render() {
    return (
      <Router>
        <div className='container'>
          <Nav />
          <Switch>
            <Route exact path='/' component={Home} />
            <Route path='/popular' component={Popular} /> //RIGHT HERE
            <Route render={function() {
              return <p>Not found</p>
            }} />
          </Switch>
        </div>
      </Router>
    )
  }
}

尽管在网上进行了研究,但我很难理解为什么会这样。当我在historyApiFallback: true下面添加publicPath: '/'webpack.config.js时,它就起作用了:

let path = require('path');
let HtmlWebpackPlugin = require('html-webpack-plugin');

module.exports = {
  entry: './app/index.js',
  output: {
    path: path.resolve(__dirname, 'dist'),
    filename: 'index_bundle.js',
    publicPath: '/' //Sets base path for our assets
  },
  module: {
    rules: [
      {
        test: /\.(js)$/,
        use: 'babel-loader'
      },
      {
        test: /\.(css)$/,
        use: ['style-loader', 'css-loader']
      }
    ]
  },
  devServer: {
    historyApiFallback: true
  },
  plugins: [new HtmlWebpackPlugin({
    template: 'app/index.html'
  })]
}

这是我的index.html,当它由Webpack生成时:

<!DOCTYPE html>
<html en="lang">
  <head>
    <meta charset="utf-8"/>
    <title>Github Battle</title>
  </head>
  <body>
    <div id="app"></div>
  <script type="text/javascript" src="index_bundle.js"></script></body>
</html>

我的问题是,为什么webpack中的这两个属性使它工作,为什么在localhost:8080/而不是localhost:8080/popular上加载应用程序时它会起作用?

0 个答案:

没有答案