【发布时间】:2020-03-25 18:07:14
【问题描述】:
我正在尝试通过 JavaScript 检查/验证 URL 是否存在。而且我发现了一些应该可以工作的代码。
但是,我遇到了 CORS 错误。似乎我的请求一直被阻止:
在“https://www.google.co.uk/”访问 XMLHttpRequest(重定向 from 'http://www.google.co.uk/') from origin 'null' 已被阻止 通过 CORS 策略:不存在“Access-Control-Allow-Origin”标头 请求的资源。
如何在没有服务器端代码的情况下使用 JS 解决这个问题?我想完全在前端/客户端处理这个:
var MrChecker = new XMLHttpRequest(),
CheckThisUrl = "http://www.google.co.uk";
// Opens the file and specifies the method (get)
// Asynchronous is true
MrChecker.open('get', CheckThisUrl, true);
//check each time the ready state changes
//to see if the object is ready
MrChecker.onreadystatechange = checkReadyState;
function checkReadyState() {
if (MrChecker.readyState === 4) {
//check to see whether request for the file failed or succeeded
if ((MrChecker.status == 200) || (MrChecker.status == 0)) {
console.log(CheckThisUrl + ' page is exixts');
}
else {
console.log(CheckThisUrl + ' not exists');
return;
}
}
}
MrChecker.send(null);
【问题讨论】:
标签: javascript validation cors xmlhttprequest http-headers