【发布时间】:2020-05-05 19:25:45
【问题描述】:
我想设置 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 );
}
}
【问题讨论】:
-
你会想要使用 NodeJS,而不是客户端 javascript。
-
你是个了不起的人,NodeJS 运行良好。非常感谢^^
标签: javascript xmlhttprequest http-headers