【问题标题】:react.js with webpack Resource blocked due to MIME type mismatch由于 MIME 类型不匹配,带有 webpack 资源的 react.js 被阻止
【发布时间】:2020-04-09 09:10:50
【问题描述】:

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

App.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"
        })
    ]
};

【问题讨论】:

  • 您是否使用express 作为后端?

标签: reactjs webpack react-router


【解决方案1】:

我遇到了同样的问题,并通过在module.exportsoutput 选项中添加publicPath: '/dist/' 解决了这个问题webpack.config.js

【讨论】:

    【解决方案2】:

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

    content-type: "text\javasscript"
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-08-11
      • 2021-03-21
      • 2021-02-23
      • 2019-10-14
      • 2020-06-20
      • 1970-01-01
      • 2021-01-10
      • 1970-01-01
      相关资源
      最近更新 更多