react.js with webpack Resource blocked due to MIME type mismatch, when accessing an url params with react router

谁说胖子不能爱 提交于 2021-01-07 07:46:25

问题


When I try to access the URL like for example localhost:8080/edit/12 I get an error on the console and I can't access the id from it, is it the problem in the versions used on the package.json or in the webpack config file?

Component EditExpensePage:

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

Component router 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 config file:

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"),
  },
};

回答1:


I found the solution by converting the component EditExpensePage to a class component, and it worked.

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>
    );
  }
}



回答2:


When you request localhost:8080/edit/12 you serve the index.html, and presumably, that is done for every resource that doesn't exist on your server (as a fallback). I assume, in the index.html you have the following script tag:

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

This is a relative path. You are actually requesting localhost:8080/edit/bundle.js at this point and because that doesn't exist, you end up serving the index.html as the bundle, which is problematic because it's not valid JavaScript.

You should always use /bundle.js regardless of the current URL. Similarly, you'd always want /styles.css for your CSS.

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


来源:https://stackoverflow.com/questions/61033215/react-js-with-webpack-resource-blocked-due-to-mime-type-mismatch-when-accessing

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!