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

IT技术 reactjs webpack react-router
2021-05-09 23:59:32

使用 webpack 开发 React 应用程序,在我的 app.js 路由器中,当我将路由指定为 /foo 时,组件正常呈现,但是当我将路由指定为 /foo/bar 时,我收到以下错误“来自“ http:/的资源” /localhost:9000/foo/bar/bundle.js ”由于 MIME 类型(“text/html”)不匹配(X-Content-Type-Options:nosniff)而被阻止”

应用程序.js

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

webpack.config.js

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


module.exports = {
    entry: path.resolve(__dirname, 'src/index'),
    output:{
        path: path.resolve(__dirname, 'dist'),
        filename: 'bundle.js',
    },
    module:{
        rules: [
            {
                test: /\.(js|jsx)$/,
                exclude: /node_modules/,
                use: [
                    {
                        loader: 'babel-loader',
                        options: {
                            presets: ['@babel/react']
                        }
                    }
                ]
            },
            {
                test: /\.css$/,
                exclude: /node_modules/,
                use:[
                    {loader: 'style-loader'},
                    {loader: 'css-loader'}
                ]               
            },]
    },
    devServer:{
        contentBase: path.resolve(__dirname, 'dist'),
        port: 9000,
        historyApiFallback: true
    },
    plugins:[
        new HtmlWebpackPlugin({
            template: "src/index.html"
        })
    ]
};
2个回答

我正面临同样的问题,并通过添加解决它publicPath: '/dist/'output的选项module.exportswebpack.config.js

尝试将内容类型更改为“text/javasscript”。

content-type: "text\javasscript"