我正在尝试在移动设备上测试我的React应用程序。我使用ngrok将本地服务器提供给其他设备,并且已经成功地与各种其他应用程序配合使用。但是,当我尝试将ngrok连接到React开发服务器时,会出现以下错误:
Invalid Host Header
我认为React默认会阻止来自其他源的所有请求。你有什么想法吗?
我遇到了类似的问题,找到了两个解决方案,在直接在浏览器中查看应用程序方面都有效。
ngrok http 8080 --host-header="localhost:8080"
ngrok http --host-header=rewrite 8080
很明显,用你正在运行的端口号替换8080
当我在嵌入页面中使用它并从React应用程序中提取bundle.js时,此解决方案仍会引发错误。 我认为由于它在嵌入式页面中重写了标题为localhost,因此它正在查找本地主机,而应用程序已不再运行。
选项1
如果您不需要使用身份验证,您可以向ngrok命令添加配置。
ngrok http 9000 --host-header=rewrite
或者
ngrok http 9000 --host-header="localhost:9000"
但在这种情况下,身份验证将无法在您的网站上工作,因为ngrok正在重写标头和会话对于您的ngrok域无效。
选项2
如果您正在使用webpack,您可以添加以下配置。
devServer: {
disableHostCheck: true
}
在这种情况下,身份验证标头将对您的ngrok域名有效
allowedHosts
:allowedHosts:['your.hostname.com']
,或者更危险的allowedHosts:'all'
。 - tryforcefulngrok http https://localhost:4200 --host-header="localhost:4200"
这可能对其他人有用。ngrok http https://localhost:4200 --host-header="localhost:4200"
。 - t qdevServer: {
contentBase: path.join(__dirname, './dist'),
compress: true,
host: 'localhost',
// host: '0.0.0.0',
port: 8080,
disableHostCheck: true //for ngrok
},
我在一款正常运行的React应用中使用了这个设置。我创建了一个名为configstrp.js的配置文件,其中包含以下内容:
module.exports = {
ngrok: {
// use the local frontend port to connect
enabled: process.env.NODE_ENV !== 'production',
port: process.env.PORT || 3000,
subdomain: process.env.NGROK_SUBDOMAIN,
authtoken: process.env.NGROK_AUTHTOKEN
}, }
在服务器中引用文件。
const configstrp = require('./config/configstrp.js');
const ngrok = configstrp.ngrok.enabled ? require('ngrok') : null;
if (ngrok) {
console.log('If nGronk')
ngrok.connect(
{
addr: configstrp.ngrok.port,
subdomain: configstrp.ngrok.subdomain,
authtoken: configstrp.ngrok.authtoken,
host_header:3000
},
(err, url) => {
if (err) {
} else {
}
}
);
}
如果您没有自定义域名,请不要传递子域名
ngrok http <url> --host-header=<host>:<port>