配置ngrok&39;的CORS标头 [英] Configure ngrok's CORS headers
问题描述
我运行的是本地Web服务器,该服务器向同样从我的PC运行的ngrok服务器运行XHR请求。
我收到XMLHttpRequest cannot load http://foo.ngrok.io/. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access
。
ngrok常见问题似乎提到了CORS标头,但仅与基本身份验证相关-它没有提到如何设置标头,以便我可以在开发中测试我的应用。
如何更改ngrok的CORS选项以允许从localhost加载请求?
更新:不同的用例。此解决方案的奖金:
我收到以下错误:
login.php:1 Access to XMLHttpRequest at 'http://localhost/lagin/public/login.php'
from origin 'http://062b-96-230-240-153.ngrok.io' has been blocked by CORS
policy: The request client is not a secure context and the resource is in more-
private address space `local`.
我已经研究了配置ngrok的CORS标头,但仍然不确定如何继续。当我尝试ngrok http-host-header=rewrite 80时,它显示标题未定义。
我看了10到12个YouTube视频,它们都很好地解释了什么是CORS,但解释如何修复它却很糟糕。
我在Windows10机器上运行VirtualBox并创建一个Linux虚拟机。在Linux端,我将Xampp作为本地服务器运行。
我很乐意提供更多详细信息,但我只是不知道还需要哪些其他信息。
我可以在ngrok上看到我的网站的登录页,但是一旦我调用axios,就会收到上面的错误。
另外,我在Chrome中尝试了//flags/#block-insecure-private-network-requests,并将其设置为禁用。当我这样做时,我不再收到该错误,但网站无法工作。
其他信息:
我与ngrok交谈过,他们说:……听起来您的应用程序正在尝试调用Ajax请求中的某个localhost
。您需要调整该呼叫以确保其通过ngrok路由。
我正在做的是:
responseData = sendData2('http://localhost/lagin/public/login.php',emailPass);
这里是sendData2(仅为完整起见)
function sendData2(url,emailPass){
let bodyFormData = new FormData()
for (const [key, value] of Object.entries(emailPass)) {
//console.log(key,value)
bodyFormData.append(key,value)
}
return axios({
method: 'POST',
url: url,
data: bodyFormData,
headers: {'Content-Type': 'multipart/form-data'}
})
.then(function(response){
return response.data
})
.catch(function(response){
return response
})
}
更新:如果我们将send2()调用更改为
,则每次我们通过隧道进入ngrok时都会得到一个类似https://2634-96-230-240-153.ngrok.io的地址sendData2('http://96-230-240-153.ngrok.io/lagin/public/login.php',emailPass);
它可以工作,但这要求我每次有新隧道时都要更改代码。调整CORS政策能绕过这个问题吗?
推荐答案
我今天偶然发现了这个问题,可以通过启动ngrok
并包含-host-header
标志来解决它。
ngrok http -host-header=rewrite 3000
来自文档:
使用
如果指定重写,则主机标头将被重写以匹配 转发地址的主机名部分。-host-header
开关重写传入的HTTP请求。
这篇关于配置ngrok&39;的CORS标头的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!