react.js with webpack使用react router访问url参数时,由于MIME类型不匹配,资源被阻止

kgqe7b3p  于 11个月前  发布在  Webpack
关注(0)|答案(3)|浏览(159)

当我尝试访问URL时,例如localhost:8080/edit/12,我在控制台上得到一个错误,我无法从它访问ID,这是package.json上使用的版本还是webpack配置文件中的问题?
组件编辑费用页面:

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

vlf7wbxs

vlf7wbxs1#

当你请求localhost:8080/edit/12时,你提供了index.html,大概,这是为你的服务器上不存在的每一个资源做的(作为后备)。我假设,在index.html中,你有以下脚本标记:

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

字符串
这是一个相对路径。此时您实际上正在请求localhost:8080/edit/bundle.js,因为它不存在,您最终将index.html作为bundle提供,这是有问题的,因为它不是有效的JavaScript。
无论当前URL是什么,你都应该使用/styles. js。同样,你的CSS也应该使用/styles. css。

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

l7mqbcuq

l7mqbcuq2#

我通过将组件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>
    );
  }
}

字符串

mwg9r5ms

mwg9r5ms3#

对我来说,帮助是Github上的这条评论。我不得不将publicPath: '/'添加到我的Webpack配置中:

// ...
  output: {
    // ...
    publicPath: '/',
  },
// ...

字符串

相关问题