我在Cloud9.io上的Webpack开发服务器中运行我的React应用程序时收到“Invalid Host header”消息

时间:2017-04-25 19:45:46

标签: reactjs webpack-dev-server cloud9-ide cloud9

我使用的是一个环境,一个Cloud9.io ubuntu VM Online IDE,我通过对此错误进行故障排除,只是通过Webpack dev服务器运行应用程序。

我用:

启动它
webpack-dev-server -d --watch --history-api-fallback --host $IP --port $PORT

$ IP是具有主机地址的变量 $ PORT有端口号。

我被指示在Cloud 9中部署应用时使用这些变量,因为它们具有默认的IP和PORT信息。

服务器启动并编译代码,没问题,但显示我的索引文件。只有一个带有“无效主机标题”的空白屏幕作为文本。

这是请求:

GET / HTTP/1.1
Host: store-client-nestroia1.c9users.io
Connection: keep-alive
Pragma: no-cache
Cache-Control: no-cache
Upgrade-Insecure-Requests: 1
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 
(KHTML, like Gecko) Chrome/57.0.2987.133 Safari/537.36
Accept: 
text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8
DNT: 1
Accept-Encoding: gzip, deflate, sdch, br
Accept-Language: en-US,en;q=0.8

这是我的package.json:

{
  "name": "workspace",
  "version": "0.0.0",
  "scripts": {
    "dev": "webpack -d --watch",
    "server": "webpack-dev-server -d --watch --history-api-fallback --host $IP --port $PORT",
    "build": "webpack --config webpack.config.js"
  },
  "author": "Artur Vieira",
  "license": "ISC",
  "dependencies": {
    "babel-core": "^6.18.2",
    "babel-loader": "^6.2.8",
    "babel-preset-es2015": "^6.18.0",
    "babel-preset-react": "^6.16.0",
    "babel-preset-stage-0": "^6.24.1",
    "file-loader": "^0.11.1",
    "node-fetch": "^1.6.3",
    "react": "^15.5.4",
    "react-bootstrap": "^0.30.9",
    "react-dom": "^15.5.4",
    "react-router": "^4.1.1",
    "react-router-dom": "^4.1.1",
    "url-loader": "^0.5.8",
    "webpack": "^2.4.1",
    "webpack-dev-server": "^2.4.4",
    "whatwg-fetch": "^2.0.3"
  }
}

这是webpack.config.js:

const path = require('path');

module.exports = {

  entry: ['whatwg-fetch', "./app/_app.jsx"], // string | object | array
  // Here the application starts executing
  // and webpack starts bundling
  output: {
    // options related to how webpack emits results

    path: path.resolve(__dirname, "./public"), // string
    // the target directory for all output files
    // must be an absolute path (use the Node.js path module)

    filename: "bundle.js", // string
    // the filename template for entry chunks

    publicPath: "/public/", // string
    // the url to the output directory resolved relative to the HTML page
  },

  module: {
    // configuration regarding modules

    rules: [
      // rules for modules (configure loaders, parser options, etc.)
      {
        test: /\.jsx?$/,
        include: [
          path.resolve(__dirname, "./app")
        ],
        exclude: [
          path.resolve(__dirname, "./node_modules")
        ],
        loader: "babel-loader?presets[]=react,presets[]=es2015,presets[]=stage-0",
        // the loader which should be applied, it'll be resolved relative to the context
        // -loader suffix is no longer optional in webpack2 for clarity reasons
        // see webpack 1 upgrade guide
      },
      {
        test: /\.css$/,
        use: [ 'style-loader', 'css-loader' ]
      },
      {
        test: /\.(png|jpg|jpeg|gif|svg|eot|ttf|woff|woff2)$/,
        loader: 'url-loader',
        options: {
          limit: 10000
        }
      }
    ]
  },

  devServer: {
    compress: true
  }
}

由于我的主机设置,Webpack dev服务器正在返回此状态。在webpack-dev-server / lib / Server.js第60行。来自https://github.com/webpack/webpack-dev-server

我的问题是我如何设置正确通过此检查。任何帮助将不胜感激。

14 个答案:

答案 0 :(得分:233)

我用这个解决了,因为webpack-dev-server 2.4.4添加主机检查

000003I000000 000000 000010 000005I000000 000000
000000 000000 000000 000000 000000 000000 000000
000000 000000 000000 000000 000000 000000 000000

编辑:请注意,此修复程序不安全。

有关安全的解决方案,请参阅以下答案: https://stackoverflow.com/a/43621275/5425585

答案 1 :(得分:74)

我发现,我需要将devServer的public属性设置为我的请求的主机值。因为它将显示在该外部地址。

所以我在webpack.config.js

中需要这个
devServer: {
  compress: true,
  public: 'store-client-nestroia1.c9users.io' // That solved it
}

另一种解决方案是在CLI上使用它:

webpack-dev-server --public $ C9_HOSTNAME< - var for Cloud9 external IP

答案 2 :(得分:25)

这对我有用:

在webpack.config.js的devServer下添加allowedHosts:

devServer: {
  compress: true,
  inline: true,
  port: '8080',
  allowedHosts: [
      '.amazonaws.com'
  ]
},

我不需要使用--host或--public参数。

答案 3 :(得分:9)

使用webpack-dev-server时,将此配置添加到webpack配置文件中(您仍然可以将主机指定为0.0.0.0)。

devServer: {
    disableHostCheck: true,
    host: '0.0.0.0',
    port: 3000
}

答案 4 :(得分:6)

禁用主机检查的简单方法是编辑event.stopPropafgation()文件到您的根文件夹,然后放置以下内容,而不是编辑webpack配置文件:

.env

正如变量名所暗示的那样,禁用它是不安全的,仅在开发环境中建议使用。

答案 5 :(得分:2)

如果您在C9上使用create-react-app,只需运行此命令即可启动

npm run start --public $C9_HOSTNAME

从您的主机名访问应用程序(例如,在终端中键入$C_HOSTNAME以获取主机名)

答案 6 :(得分:2)

如果您正在容器中运行webpack-dev-server,并通过其容器名称向其发送请求,则会收到此错误。要允许来自同一网络上其他容器的请求,只需使用--public选项提供容器名称(或用于解析容器的任何名称)。这比完全禁用安全检查要好。

在我的情况下,我在带有docker-compose的名为webpack-dev-server的容器中运行assets。我将启动命令更改为:

webpack-dev-server --mode development --host 0.0.0.0 --public assets

另一个容器现在可以通过http://assets:5000发出请求。

答案 7 :(得分:1)

你好反应开发人员

而不是这样做 {strong> webpackDevServer.config.js 中的disableHostCheck: true,。您可以通过在项目中添加一个 .env 文件,添加变量 HOST = 0.0.0.0 并轻松解决“无效的主机头” 错误。 .env 文件中的 DANGEROUSLY_DISABLE_HOST_CHECK = true 。如果要在 webpackDevServer.config.js 中进行更改,则需要使用'npm run弹出'提取反应脚本,不建议这样做。因此,更好的解决方案是在项目的 .env 文件中添加上述变量。

快乐编码:)

答案 8 :(得分:1)

我刚刚在使用适用于 Linux 的 Windows 子系统 (WSL2) 时遇到了这个问题,所以我也会分享这个解决方案。

我的目标是在 wsl:3000localhost:3000 处呈现 webpack 的输出,从而创建一个备用的本地端点。

如您所料,这最初会导致出现“无效主机标头”错误。在我添加如下所示的 devServer 配置选项之前,似乎没有任何帮助。


module.exports = {
  //...
  devServer: {
    proxy: [
      {
        context: ['http://wsl:3000'],
        target: 'http://localhost:3000',
      },
    ],
  },
}

这在不引入任何安全风险的情况下修复了“错误”。

参考:webpack DevServer docs

答案 9 :(得分:0)

更安全的选择是像这样将allowedHosts添加到您的Webpack配置中:

module.exports = {
devServer: {
 allowedHosts: [
  'host.com',
  'subdomain.host.com',
  'subdomain2.host.com',
  'host2.com'
   ]
  }
};

该数组包含所有允许的主机,还可以指定子域。 check out more here

答案 10 :(得分:0)

如果尚未从CRA中退出,则无法轻松修改Webpack配置。配置文件隐藏在node_modules/react_scripts/config/webpackDevServer.config.js中。不鼓励您更改该配置。

相反,您只需将环境变量DANGEROUSLY_DISABLE_HOST_CHECK设置为true即可禁用主机检查:

DANGEROUSLY_DISABLE_HOST_CHECK=true yarn start  
# or the equivalent npm command

答案 11 :(得分:0)

我通过在 nginx 配置中添加主机头的代理解决了这个问题,如下所示:

server {
    listen 80;
    server_name     localhost:3000;

    location / {
        proxy_pass http://myservice:8080/;

        proxy_set_header HOST $host;
        proxy_set_header Referer $http_referer;
    }
}

我补充说:

proxy_set_header HOST $host;

proxy_set_header Referer $http_referer;

答案 12 :(得分:0)

从 webpack-dev-server 4 开始,您需要将其添加到您的配置中:

devServer: {
  firewall: false,
}

答案 13 :(得分:0)

在与这篇文章相关的 webpack 5 中使用默认行为(无配置文件)时:[https://stackoverflow.com/a/65268634/2544762`]

public void run() {
        try {
            String url = this.user.getServer().getUrlTransfer();
            Document data = new Document();
            data.put("nickNameRecv", this.nickNameRecv);
            data.put("otp", otp);
            String authorization = "Bearer " +
                    this.user.getAuth();
            URL urlCon = new URL(url);
            HttpURLConnection connection;
            final String authUser = this._proxy.getProxyUserName();
            final String authPassword = this._proxy.getProxyPassword();
            Authenticator.setDefault(new ProxyAuthenticator(authUser, authPassword));
            Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(this._proxy.getProxyHost(), this._proxy.getProxyPort()));
            if (_proxy == null)
                connection = (HttpURLConnection) urlCon.openConnection();
            else
                connection = (HttpURLConnection) urlCon.openConnection(proxy);
            connection.setRequestMethod("POST");
            connection.setConnectTimeout(timeout);
            connection.setReadTimeout(timeout);
            connection.setRequestProperty(HttpHeaders.ACCEPT, ContentType.APPLICATION_JSON.toString());
            connection.setRequestProperty(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_JSON.toString());
            connection.setRequestProperty(HttpHeaders.AUTHORIZATION, authorization);connection.setRequestProperty("client-browser", "Chrome 83");
//                connection.setRequestProperty("client-deviceid", rand(32, -1, "abcdef1234567890"));
            connection.setRequestProperty("client-operatingsystem", "Windows");
            String param = data.toJson();
            connection.setRequestProperty("Content-Length", String.valueOf(param.length()));
            connection.setRequestProperty(HttpHeaders.USER_AGENT, Main.agent.get(new Random().nextInt(Main.agent.size())));
            connection.setDoOutput(true);
            OutputStream outputStream = connection.getOutputStream();
            outputStream.write(param.getBytes());

            InputStream inputStream = connection.getInputStream();

            ObjectMapper mapper = new ObjectMapper();
            Map res = mapper.readValue(inputStream, Map.class);

            outputStream.close();
            inputStream.close();
            connection.disconnect();
            ProcessGame.done++;
            Main.f.updateResult();
        } catch (Exception e) {
            ProcessGame.failList.add(Integer.parseInt(this.otp));
        }
    }

使用 webpack 5 帮助"scripts": { "dev": "webpack serve --mode development --env development --hot --port 3000" ... ... }, "devDependencies": { ... "webpack": "^5.10.1", "webpack-cli": "^4.2.0" },

webpack serve --help

解决方案

因此,只需在 Usage: webpack serve|server|s [entries...] [options] Run the webpack dev server. Options: -c, --config <value...> Provide path to a webpack configuration file e.g. ./webpack.config.js. --config-name <value...> Name of the configuration to use. -m, --merge Merge two or more configurations using 'webpack-merge'. --env <value...> Environment passed to the configuration when it is a function. --node-env <value> Sets process.env.NODE_ENV to the specified value. --progress [value] Print compilation progress during build. -j, --json [value] Prints result as JSON or store it in a file. -d, --devtool <value> Determine source maps to use. --no-devtool Do not generate source maps. --entry <value...> The entry point(s) of your application e.g. ./src/main.js. --mode <value> Defines the mode to pass to webpack. --name <value> Name of the configuration. Used when loading multiple configurations. -o, --output-path <value> Output location of the file generated by webpack e.g. ./dist/. --stats [value] It instructs webpack on how to treat the stats e.g. verbose. --no-stats Disable stats output. -t, --target <value...> Sets the build target e.g. node. --no-target Negative 'target' option. --watch-options-stdin Stop watching when stdin stream has ended. --no-watch-options-stdin Do not stop watching when stdin stream has ended. --bonjour Broadcasts the server via ZeroConf networking on start --lazy Lazy --liveReload Enables/Disables live reloading on changing files --serveIndex Enables/Disables serveIndex middleware --inline Inline mode (set to false to disable including client scripts like livereload) --profile Print compilation profile data for progress steps --progress Print compilation progress in percentage --hot-only Do not refresh page if HMR fails --stdin close when stdin ends --open [value] Open the default browser, or optionally specify a browser name --useLocalIp Open default browser with local IP --open-page <value> Open default browser with the specified page --client-log-level <value> Log level in the browser (trace, debug, info, warn, error or silent) --https HTTPS --http2 HTTP/2, must be used with HTTPS --key <value> Path to a SSL key. --cert <value> Path to a SSL certificate. --cacert <value> Path to a SSL CA certificate. --pfx <value> Path to a SSL pfx file. --pfx-passphrase <value> Passphrase for pfx file. --content-base <value> A directory or URL to serve HTML content from. --watch-content-base Enable live-reloading of the content-base. --history-api-fallback Fallback to /index.html for Single Page Applications. --compress Enable gzip compression --port <value> The port --disable-host-check Will not check the host --socket <value> Socket to listen --public <value> The public hostname/ip address of the server --host <value> The hostname/ip address the server will bind to --allowed-hosts <value...> A list of hosts that are allowed to access the dev server, separated by spaces Global options: --color Enable colors on console. --no-color Disable colors on console. -v, --version Output the version number of 'webpack', 'webpack-cli' and 'webpack-dev-server' and commands. -h, --help [verbose] Display help for commands and options. To see list of all supported commands and options run 'webpack --help=verbose'. Webpack documentation: https://webpack.js.org/. CLI documentation: https://webpack.js.org/api/cli/. Made with ♥ by the webpack team. Done in 0.44s. 命令中添加 --disable-host-check 即可。