首页 > 解决方案 > 为 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 );       
        }   
    }   

标签: javascriptxmlhttprequesthttp-headers

解决方案


默认情况下,浏览器会阻止从网页访问其他网站的网页。可以使用浏览器设置来允许它。为此不存在其他方法。但是,可以使用 GET 或 POST 将某些数据发布到另一个网站,例如在支付网关的情况下。


推荐阅读