2 回答

TA貢獻(xiàn)2041條經(jīng)驗(yàn) 獲得超4個(gè)贊
您可以發(fā)出 HEAD 請求以查看 URL 是否存在。也許是這樣的。
async function exists(url) {
const result = await fetch(url, { method: 'HEAD' });
return result.ok;
}

TA貢獻(xiàn)1811條經(jīng)驗(yàn) 獲得超6個(gè)贊
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>
);
}
}
查看以下網(wǎng)址中的代碼示例:
https://codesandbox.io/s/loving-napier-dpli5
添加回答
舉報(bào)