由于 MIME 类型不匹配,react.js 与 webpack 资源被阻止

JAY*_*AYC 5 reactjs webpack react-router

使用 webpack 开发一个 React 应用程序,在我的 app.js 路由器中,当我将路由指定为 /foo 时,组件正常渲染,但是当我将路由指定为 /foo/bar 时,我收到以下错误\n“来自 \xe2 的资源\x80\x9c http://localhost:9000/foo/bar/bundle.js \xe2\x80\x9d 由于 MIME 类型 (\xe2\x80\x9ctext/html\xe2\x80\x9d) 不匹配 (X -内容类型选项:nosniff)”

\n\n

应用程序.js

\n\n
function App() {\n    return (\n        <div className="App">\n            <BrowserRouter>\n                <Router history={history}>\n                    <Switch>\n                        <Route exact path="/api/login" component={Login} /> //gives error\n                        <Route exact path="/login" component={Login} /> //renders normally\n                        <Route component={Error} />\n                    </Switch>\n                </Router>\n            </BrowserRouter>\n        </div>\n    );\n}\n
Run Code Online (Sandbox Code Playgroud)\n\n

Webpack.config.js

\n\n
const path = require(\'path\');\nconst HtmlWebpackPlugin = require(\'html-webpack-plugin\');\n\n\nmodule.exports = {\n    entry: path.resolve(__dirname, \'src/index\'),\n    output:{\n        path: path.resolve(__dirname, \'dist\'),\n        filename: \'bundle.js\',\n    },\n    module:{\n        rules: [\n            {\n                test: /\\.(js|jsx)$/,\n                exclude: /node_modules/,\n                use: [\n                    {\n                        loader: \'babel-loader\',\n                        options: {\n                            presets: [\'@babel/react\']\n                        }\n                    }\n                ]\n            },\n            {\n                test: /\\.css$/,\n                exclude: /node_modules/,\n                use:[\n                    {loader: \'style-loader\'},\n                    {loader: \'css-loader\'}\n                ]               \n            },]\n    },\n    devServer:{\n        contentBase: path.resolve(__dirname, \'dist\'),\n        port: 9000,\n        historyApiFallback: true\n    },\n    plugins:[\n        new HtmlWebpackPlugin({\n            template: "src/index.html"\n        })\n    ]\n};\n
Run Code Online (Sandbox Code Playgroud)\n

小智 3

我遇到了同样的问题,并通过添加in选项publicPath: '/dist/'解决了它。outputmodule.exportswebpack.config.js