SaA*_*mic 4 javascript http access-control
我想检查是否可以使用 JavaScript 函数访问服务器。
通过reachable,我的意思是,如果服务器应答,我不在乎哪个HTTP 状态代码,它是可达的。
Stackoverflow/Google 帮我实现了这个功能:
function check(target)
{
var xhr = new XMLHttpRequest();
var target = "https://"+target+"/index.php";
var num = Math.round(Math.random() * 10000);
xhr.open("HEAD", target + "?num=" + num, true);
xhr.send();
xhr.addEventListener("readystatechange", processRequest, false);
function processRequest(e)
{
if (xhr.readyState == 4)
{
if (xhr.status !== 0)
{
return true;
}
else
{
return false;
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
如果目标允许与Access-Control-Allow-Origin: *(或特别是客户端)进行操作,则效果很好。但事实并非如此。
我遇到了许多解决方案,它们似乎都依赖于此。
如何Access-Control-Allow-Origin使用 JavaScript独立于服务器上的设置检查服务器是否可访问?
编辑:我只是想补充一点,我无法修改目标(例如更改标题),但我能够识别应该可用的资源(例如https://target/this-specific-site.php )
编辑2:正如@Vic 所建议的那样,我正在尝试实施一个解决方案;在这里试试:
function chk(){
var img = new Image(); // Create new image element
img.onload = function(){
return false;
};
img.onerror = function() {
return true;
};
// Try to change this URL to nonexistant image
img.src = 'https://www.google.com/images/srpr/logo3w.png'; // Set source path
}
if (chk())
{
alert("IMAGE LOADED");
}
else
{
alert("IMAGE FAILED TO LOAD ("+chk()+")");
}
Run Code Online (Sandbox Code Playgroud)
但该函数似乎返回undefined,因此检查失败。
edit3:我需要函数来给我一个返回值。
在现代浏览器中,您可以使用fetch API及其no-cors请求模式,它将返回opaque响应(您将无法从中执行任何其他操作):
fetch('http://google.com', {mode: 'no-cors'}).then(r=>{
console.log('google is reachable');
})
.catch(e=>{
console.log('google is not there');
});
fetch('http://fakeservertahtdoesntexist.com', {mode: 'no-cors'}).then(r=>{
console.log('fake is reachable');
})
.catch(e=>{
console.log('fake is not there');
});Run Code Online (Sandbox Code Playgroud)
奇怪的是,虽然我的 FF 没有抛出(但它也没有),而我的 chrome 确实抛出了。