如何使用React检查远程源是否可用?

5

我想检查远程资源是否存在(例如一个非常巨大的zip文件,但我不需要收集该文件)。那么什么是最好的方法只是检查资源的存在性?

2个回答

6

您可以发送HEAD请求来查看URL是否存在。类似这样的代码:

async function exists(url) {
  const result = await fetch(url, { method: 'HEAD' });
  return result.ok;
}

1
import React from "react";
import "./styles.css";

export default class App extends React.Component {
  state = { isFileExists: false };
  componentDidMount() {
    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


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接