javascript - 为 iframe 设置自定义 HTTP 请求标头
问题描述
我想设置 2 个 HTTP 请求标头(X-Forwarded-For 和用户代理)并显示我用 HTML 中的 iframe 发送自定义标头的网站。所以我开始写一个JavaScript,它工作正常。它将正确的标头发送到我自己的网站,但不会连接到不是我自己托管的网站,并且我收到以下错误消息:
“从源 'http://myserver.com' 访问 'https://google.com/' 的 XMLHttpRequest 已被 CORS 策略阻止:请求的资源上不存在 'Access-Control-Allow-Origin' 标头。” .
有没有办法来解决这个问题?
这是我的 JavaScript 代码:
var xmlHttp = createXmlHttpRequestObject();
function createXmlHttpRequestObject() {
var xmlHttp;
if(window.XMLHttpRequest){
xmlHttp = new XMLHttpRequest();
}
else {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
return xmlHttp;
}
function process() {
if(xmlHttp){
try {
xmlHttp.open("GET", "https://google.com", true);
xmlHttp.setRequestHeader("X-Forwarded-For", "1.2.3.4")
xmlHttp.onreadystatechange = handleServerResponse;
xmlHttp.send(null);
}
catch(e){
alert( e.toString() );
}
}
}
function handleServerResponse() {
theD = document.getElementById('theD');
if(xmlHttp.readyState==1) {
theD.innerHTML += "Status 1: server connection established <br/>";
}
else if(xmlHttp.readyState==2){
theD.innerHTML += "Status 2: request recived <br/>";
}
else if(xmlHttp.readyState==3){
theD.innerHTML += "Status 3: processing request <br/>";
}
else if(xmlHttp.readyState==4){
if(xmlHttp.status==200) {
try {
texxt = xmlHttp.responseText;
theD.innerHTML += "Status 4: request is finsihed, response is ready <br/>";
theD.innerHTML += texxt;
}
catch(e){
alert( e.toString() );
}
}
}
else {
alert( xmlHttp.statusText );
}
}
解决方案
默认情况下,浏览器会阻止从网页访问其他网站的网页。可以使用浏览器设置来允许它。为此不存在其他方法。但是,可以使用 GET 或 POST 将某些数据发布到另一个网站,例如在支付网关的情况下。
推荐阅读
- kubernetes - 如何使用 kubectl 显示自己的信息?
- django - Django:存储所有应用程序通用功能的位置
- python - 在 if __ is __ 语句中使用 .lower 或 'or' 会导致 python 3.6 中的 if 语句流不正确
- rust - How to end borrow when an Option is None
- python-3.x - 尽管路径正确存在,但当我无法访问 sql 路径时,我应该看哪个方面?
- javascript - 为什么 [[HomeObject]] 方法的简写语法不同?
- javascript - 如何通过单击 Google 地图上的 POI 标记直接将目的地(航点)添加到路线
- amazon-web-services - AWS Cognito:是否有在身份验证期间切换 MFA 类型的方法?
- arrays - 在 Ruby 中迭代多维数组的格式
- ruby-on-rails - Ruby On Rails:命名嵌套控制器和视图的正确方法是什么