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 badges
Add a ment  | 

2 Answers 2

Reset to default 7

You 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