I've been spending nearly all day just trying to implement a rather simple feature in my React code. The basic idea is checking if a server is reachable, and if it isn't, return a console.log() indicating so. Here's what I have so far:
Relevant Code
const handleLinkRegex = () => {
fetch(LinkInput, { mode: "no-cors" })
.then((response) => {
if (response.ok || response.status === 0) {
console.log("yessir");
} else if (response.status === 404) {
return Promise.reject("error 404");
} else {
return Promise.reject("some other error: " + response.status);
}
})
.then((data) => console.log("data is", data))
.catch((error) => console.log("error is", error));
};
Output
If the link is valid, such as https://mantine.dev/core/input/
, the result is yessir
, followed with data is undefined
.
If the link is invalid and returns a 404, such as https://mantine.dev/core/input/invalidurl
, the result is a console 404 error, and yessir
, followed with data is undefined
, which is the same as if it didn't fail.
What I tried
- Using the
url-exist
library only resulted in a CORS error - Attempted to use a different solution from a stackoverflow question:
const handleLinkVerify = async () => {
fetch(LinkInput, { mode: "no-cors" })
.then((r) => {
console.log("Is reachable");
})
.catch((e) => {
console.log("Is not there");
});
};
Which resulted in every url, no matter if valid or not, to return as Is not there
.
Overall, I'm waving the white flag with dealing with a simple issue. It's taking me hours just to catch this 404 error and handle it, and no matter what green checkmark answer I read their solution doesn't work for me, for some reason. I feel like I'm missing something obvious, but I don't know what. Thanks for any help.