admin管理员组文章数量:1291315
I would like to check if the remote resource exist (for example a very huge zip file. I don't need to collect the file). So what is the best way just to check the existence of the resource?
I would like to check if the remote resource exist (for example a very huge zip file. I don't need to collect the file). So what is the best way just to check the existence of the resource?
Share Improve this question edited Mar 21, 2020 at 16:47 Dharman♦ 33.4k27 gold badges101 silver badges147 bronze badges asked Mar 21, 2020 at 14:53 WinstonWinston 1,4285 gold badges18 silver badges40 bronze badges2 Answers
Reset to default 7You can make a HEAD request to see if a URL exists. Maybe something like this.
async function exists(url) {
const result = await fetch(url, { method: 'HEAD' });
return result.ok;
}
import React from "react";
import "./styles.css";
export default class App extends React.Component {
state = { isFileExists: false };
ponentDidMount() {
this.checkFIle(window.location.origin + "/files/FL_1.zip")
.then(() => {
this.setState({ isFileExists: true });
})
.catch(err => {
this.setState({ isFileExists: false });
});
}
checkFIle = async url => {
return fetch(url, { method: "HEAD" });
};
render() {
const { isFileExists } = this.state;
return (
<div className="App">
{isFileExists && <p>File Exists</p>}
{!isFileExists && <p>File Not Exists</p>}
</div>
);
}
}
Check out the code sample in below url:
https://codesandbox.io/s/loving-napier-dpli5
本文标签: javascriptHow to check if the remote source is available using ReactStack Overflow
版权声明:本文标题:javascript - How to check if the remote source is available using React? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741527835a2383577.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论