【问题标题】:react.js with webpack Resource blocked due to MIME type mismatch, when accessing an url params with react router使用反应路由器访问 url 参数时,由于 MIME 类型不匹配而导致 webpack 资源被阻止的 react.js
【发布时间】:2020-04-04 18:54:48
【问题描述】:

当我尝试访问例如 localhost:8080/edit/12 之类的 URL 时,我在控制台上收到一个错误,我无法从中访问 id,这是包上使用的版本中的问题吗? json 或在 webpack 配置文件?

组件EditExpensePage:

import React from "react";
const EditExpensePage = (props) => {
  return (
    <div>This is from EditExpensePage component at {props.match.params.id}</div>
  );
};
export default EditExpensePage;

组件路由器AppRouter:

import React from "react";
import { BrowserRouter, Route, Switch } from "react-router-dom";
import EditExpensePage from "../components/EditExpensePage";
const AppRouter = () => (
  <BrowserRouter>
    <div>
      <Header />
      <Switch>
        <Route path="/edit/:id" component={EditExpensePage} />
      </Switch>
    </div>
  </BrowserRouter>
);

Webpack 配置文件:

const path = require("path");
module.exports = {
  entry: "./src/app.js",
  output: {
    path: path.join(__dirname, "public"),
    filename: "bundle.js",
  },
  module: {
    rules: [
      {
        loader: "babel-loader",
        test: /\.js$/,
        exclude: /node_modules/,
      },
      {
        test: /\.s?css$/,
        use: ["style-loader", "css-loader", "sass-loader"],
      },
    ],
  },
  devtool: "source-map",
  devServer: {
    contentBase: path.join(__dirname, "public"),
  },
};

【问题讨论】:

    标签: webpack webpack-dev-server react-router-dom type-mismatch


    【解决方案1】:

    当您请求 localhost:8080/edit/12 时,您会提供 index.html,并且大概是针对服务器上不存在的每个资源完成的(作为后备)。我假设,在 index.html 你有以下脚本标签:

    <script src="bundle.js"></script>
    

    这是一个相对路径。此时您实际上是在请求 localhost:8080/edit/bundle.js,因为它不存在,所以您最终将 index.html 作为捆绑包提供服务,这是有问题的,因为它不是有效的 JavaScript。

    无论当前 URL 是什么,您都应该始终使用 /bundle.js。同样,您总是希望 /styles.css 用于您的 CSS。

    <link rel="stylesheet" href="/styles.css">
    <script src="/bundle.js"></script>
    

    【讨论】:

      【解决方案2】:

      我通过将组件EditExpensePage转换为类组件找到了解决方案,并且成功了。

      import React from "react";
      
      export default class EditExpensePage extends React.Component {
        render() {
          return (
            <div>
              This is from EditExpensePage component at {this.props.match.params.id}
            </div>
          );
        }
      }
      

      【讨论】:

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