反应路由器和Webpack似乎产生错误的输出,在某些URL中给出404

时间:2018-08-23 04:20:10

标签: javascript reactjs webpack react-router-dom

我收到此错误

GET http://localhost:9000/home/index.js 404 (Not Found)
Refused to execute script from 'http://localhost:9000/home/index.js' because its MIME type ('text/html') is not executable, and strict MIME type checking is enabled.

当我尝试使用react-router-dom使用不同的URL时。例如

之类的URL
http://localhost:9000/home/x or http://localhost:9000/home/

但是在提供

之类的URL时
http://localhost:9000/home

我得到了预期的输出。 这是webpack.config.js

const HtmlWebPackPlugin = require("html-webpack-plugin");

var config = {
   mode:'none',
   entry: './main.js',
   output: {
      path:__dirname+'/',
      filename:'index.js',
      publicPath: '/'
   },
   devServer: {
      inline: true,
      historyApiFallback:true,
      contentBase: './',
      port: 9000
   },
   plugins: [
    new HtmlWebPackPlugin({
      template: __dirname+"/index.html"

    })
   ],
   module: {
      rules: [
         {
            test: /\.(js|jsx)$/,
            exclude: /node_modules/,
            use:{
               loader: 'babel-loader',
               query: {
                   presets: ['env', 'react']
               }
            },

         }
      ]
   },
}
module.exports = config;

这是路由器文件

export default class MainBody extends React.Component{
  render(){
    return(
      <Switch>
        <Route exact path='/' component={Home}/>
        <Route path ='/addticket' component={AddTicket}/>
        <Route path ='/profile' component={ProfileBox}/>
        <Route path ='/login' component={LoginForm}/>
        <Route path = '/newhome' component={NewHome}/>
        <Route component={NotFound}/>
      </Switch>
    );
  }
}

此组件呈现在App组件内部,该组件呈现使用react-bootstrap编写的简单NavbarApp组件呈现在主路由器内部

<BrowserRouter>
    <App/>
</BrowserRouter>

,稍后使用react-dom的渲染方法进行渲染。 我从代码中期望的是,给定的URL(除上述URL之外)是NotFound组件的呈现。但这会在与以下

不一样的URL中产生上述错误。
http://localhost:9000/anything

这是package.json文件

"main": "main.js",
  "scripts": {
    "start": "webpack-dev-server --hot"
  },
  "license": "MIT",
  "peerDependencies": {
    "babel-core": "^6.26.3",
    "babel-loader": "^7.1.5",
    "babel-preset-env": "^1.7.0",
    "babel-preset-react": "^6.24.1",
    "extract-text-webpack-plugin": "^3.0.2",
    "html-loader": "^0.5.5",
    "html-webpack-plugin": "^3.2.0",
    "react": "^16.4.1",
    "react-bootstrap": "^0.32.1",
    "react-dom": "^16.4.1",
    "react-router-dom": "^4.3.1",
    "webpack": "^4.16.2",
    "webpack-dev-server": "^3.1.5"
  },
  "devDependencies": {
    "webpack-cli": "^3.1.0"
  }

0 个答案:

没有答案