tar*_*riq 7 javascript fetch cors
我的用例:我正在尝试向https://www.google.com发出简单的 fetch GET 请求来检查互联网连接。我需要检查响应代码,并根据该代码确定用户是否具有互联网连接。现在,虽然我可以在开发人员工具中看到 200 代码(没有响应标头或响应),但提取始终无法登陆到提取调用的错误处理程序中,并且控制台会标记 CORS 错误。
我确实理解,因为我正在发出跨源请求,所以这应该会导致 CORS 错误。
我想知道我该怎么做才能让我的连接代码正常工作。我显然无法更改 google.com 的响应标头。使用 google.com 的原因是因为它的可靠性,就像我们在浏览器中点击 google.com 主要是为了检查互联网是否正常工作一样:D
我的代码:
networkMonitor: () => {
const headers = new Headers();
headers.append('Cache-Control', 'no-cache');
const timerId = setInterval(() => {
fetch('https://www.google.com')
.then((response) => {
if (response.status != 200) {
// Yay ! connected
}
}, (err) => {
console.log("error: " + err); // (currently fetch failed)
})
}, 5000);
}
Run Code Online (Sandbox Code Playgroud)
PS:我知道没有办法禁用同源策略或强制其他站点发送允许所有源标头。但这可以通过使用 cors 代理来绕过。我想知道是否可以使用 google.com 或类似的现成网站来通过我的方式验证连接性,如果不能,那么从获取连接性信息的角度来看,是否有其他方法来处理它们。
您可以使用其 init 对象向 fetch 请求添加一些参数。将mode属性设置为 后no-cors,您可以向 URL 发送 GET 和 HEAD 请求,但无法访问响应。
networkMonitor: () => {
const headers = new Headers();
headers.append('Cache-Control', 'no-cache');
const timerId = setInterval(() => {
fetch('https://www.google.com', {
mode: 'no-cors'
})
.then((response) => {
if (response.status != 200) {
console.log('Yay ! connected')
}
}, (err) => {
console.log('error: ' + err);
}, 5000);
}
Run Code Online (Sandbox Code Playgroud)
另外,我会考虑发送 HEAD 请求,因为您不想使用响应正文
| 归档时间: |
|
| 查看次数: |
4059 次 |
| 最近记录: |