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

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



森林海
浏览 157回答 2
2回答

缥缈止盈

您可以发出 HEAD 请求以查看 URL 是否存在。也许是这样的。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 {&nbsp; state = { isFileExists: false };&nbsp; componentDidMount() {&nbsp; &nbsp; this.checkFIle(window.location.origin + "/files/FL_1.zip")&nbsp; &nbsp; &nbsp; .then(() => {&nbsp; &nbsp; &nbsp; &nbsp; this.setState({ isFileExists: true });&nbsp; &nbsp; &nbsp; })&nbsp; &nbsp; &nbsp; .catch(err => {&nbsp; &nbsp; &nbsp; &nbsp; this.setState({ isFileExists: false });&nbsp; &nbsp; &nbsp; });&nbsp; }&nbsp; checkFIle = async url => {&nbsp; &nbsp; return fetch(url, { method: "HEAD" });&nbsp; };&nbsp; render() {&nbsp; &nbsp; const { isFileExists } = this.state;&nbsp; &nbsp; return (&nbsp; &nbsp; &nbsp; <div className="App">&nbsp; &nbsp; &nbsp; &nbsp; {isFileExists && <p>File Exists</p>}&nbsp; &nbsp; &nbsp; &nbsp; {!isFileExists && <p>File Not Exists</p>}&nbsp; &nbsp; &nbsp; </div>&nbsp; &nbsp; );&nbsp; }}查看以下网址中的代码示例:https://codesandbox.io/s/loving-napier-dpli5
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript