WebPack Dev Server React内容安全策略错误



我的单页应用程序在WebPack-dev-server上运行。我可以在localhost:8080上加载并重新加载进入路线,并且每次都起作用。但是,我只能通过应用程序中的链接加载 localhost:8080/accounts/login,即每当我从浏览器刷新按钮重新加载localhost:8080/accounts/login时,

Cannot GET /accounts/login/

作为服务器响应,在控制台上,我得到

内容安全策略:该页面的设置阻止了加载 自我的资源(" default-src http://localhost:8080")。来源: ;(函数installglobalhook(window){....

这是我的CSP标头,在单页应用程序的index.html

<meta http-equiv="Content-Security-Policy"
  content="default-src * 'self' 'unsafe-inline' 'unsafe-eval'">

我也没有在我的webpack.config.json上使用任何devtool。我缺少什么。

如果您在项目中使用WebPack,请在WebPack配置文件中添加output.publicPath = '/'devServer.historyApiFallback = true

更多信息:React-Router URL在刷新或手动写时不起作用

我挣扎了几个小时来解决此问题。您必须添加一个简单的代码。只需按照下面的指示即可。如果您面临从特定URL浏览到另一个URL的问题,您也可以解决此问题。如果您想从WebPack配置文件进行配置,请在下面写下的代码。

devServer: {
    historyApiFallback: true
}

,如果您想通过CLI命令运行,请使用以下代码。

"start": "webpack-dev-server --history-api-fallback"

它对我有用。我不必做任何其他事情来解决此问题,例如元标记或其他内容。

如果您使用的是Rails和WebPacker并获得此错误,请注意,初始化器config/initializers/content_security_policy.rb具有Rails.env.development的内容安全策略。在该行上将:https更改为:http为我解决了错误。(请记住,就CSP而言,Localhost与127.0.0.1不同。)

添加output: { ..., publicPath: "/", }devServer: { historyApiFallback: true }工作

webpack.config.js

const path = require("path");
module.exports = {
  mode: "development",
  entry: "./src/index.js",
  output: {
    path: path.resolve(__dirname, "public"),
    filename: "main.js",
    publicPath: "/", // ++ 
  },
  target: "web",
  devServer: {
    port: "6060",
    static: ["./public"],
    open: true,
    hot: true,
    liveReload: true,
    historyApiFallback: true, // ++
  },
  resolve: {
    extensions: [".js", ".jsx", ".json", ".ts"],
  },
  module: {
    rules: [
      {
        test: /.(js|jsx)$/,
        exclude: /node_modules/,
        use: "babel-loader",
      },
      // CSS rules
      {
        test: /.css$/i,
        use: ["style-loader", "css-loader"],
      },
    ],
  },
};

我也有类似的问题。必须从webpack.config.js中的devServer配置中删除contentBase线。

这是我的webpack.config.js

var path = require("path");
module.exports = {
  devtool: 'inline-source-map',
  entry: "./src/index.js",
  output: {
    path: path.resolve(__dirname, "dist"),
    publicPath: "/assets/",
    filename: "bundle.js"
  },
  devServer: {
    port: 9002
  },
  module: {
    rules: [
      { test: /.js$/, use: 'babel-loader' }
    ]
  }
};

最新更新