所以,我的团队遇到了同样的问题,出现了相同的错误:
options.allowedHosts [0]应该是一个非空字符串。
我们下面概述的解决方案是一个非常具体的错误,很可能不适用于许多人。
在我们的情况下,
allowedHosts[0]
变量未定义,我们将
allowedHosts[0]
变量追踪到
node_modules \ react-scripts \ config \ webpackDevServer.config.js
中的
allowedHost
相等。
module.exports = function (proxy, allowedHost) {
const disableFirewall =
!proxy || process.env.DANGEROUSLY_DISABLE_HOST_CHECK === 'true';
return {
// WebpackDevServer 2.4.3 introduced a security fix that prevents remote
// websites from potentially accessing local content through DNS rebinding:
// https://github.com/webpack/webpack-dev-server/issues/887
// https://medium.com/webpack/webpack-dev-server-middleware-security-issues-1489d950874a
// However, it made several existing use cases such as development in cloud
// environment or subdomains in development significantly more complicated:
// https://github.com/facebook/create-react-app/issues/2271
// https://github.com/facebook/create-react-app/issues/2233
// While we're investigating better solutions, for now we will take a
// compromise. Since our WDS configuration only serves files in the `public`
// folder we won't consider accessing them a vulnerability. However, if you
// use the `proxy` feature, it gets more dangerous because it can expose
// remote code execution vulnerabilities in backends like Django and Rails.
// So we will disable the host check normally, but enable it if you have
// specified the `proxy` setting. Finally, we let you override it if you
// really know what you're doing with a special environment variable.
// Note: ["localhost", ".localhost"] will support subdomains - but we might
// want to allow setting the allowedHosts manually for more complex setups
allowedHosts: disableFirewall ? 'all' : [allowedHost],
urls.lanUrlForConfig
是从 node_modules\react-scripts\scripts\start.js
传递到 allowedHost
的配置文件中。
const createDevServerConfig = require('../config/webpackDevServer.config');
...
createDevServerConfig(proxyConfig, urls.lanUrlForConfig)
urls.lanUrlForCofig
是在node_modules\react-dev-utils\WebpackDevServerUtils.js
中的prepareUrls
函数生成的。
const urls = prepareUrls(
protocol,
HOST,
port,
paths.publicUrlOrPath.slice(0, -1)
);
在
prepareUrls
函数中,如果计算机的IPv4地址不是私有地址,则将
urls.lanUrlForConfig
设置为未定义,如下所示:
try {
lanUrlForConfig = address.ip();
if (lanUrlForConfig) {
if (
/^10[.]|^172[.](1[6-9]|2[0-9]|3[0-1])[.]|^192[.]168[.]/.test(
lanUrlForConfig
)
) {
lanUrlForTerminal = prettyPrintUrl(lanUrlForConfig);
} else {
lanUrlForConfig = undefined;
}
}
} catch (_e) {
}
因此,最终我们确定出现错误的原因是由于机器获取的IP地址是非私有的,这是由于某些以太网电缆配置导致的(我们得到了一个169.地址,即APIPA地址,因为机器无法连接到DHCP服务器)。这导致
urls.lanUrlForConfig
未定义,最终会传递到allowedHosts[0]变量并引起错误。
修复无法连接到DHCP服务器的问题本身就是另一个问题,但作为开发目的的临时解决方法,我们在
.env
文件中添加了
DANGEROUSLY_DISABLE_HOST_CHECK=true
,并在重新启动开发服务器后它正常工作。在我们的package.json中设置
"allowedHosts": "all"
也是另一种解决方案。