0

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

  1. Using the url-exist library only resulted in a CORS error
  2. 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.

  • What do you mean by "server exists"? In the question you say "server is reachable". If you get a `404` response it means that the server is reachable. Can you explain which underlying problem this is intended to solve? Why do you want to do that in the first place? – trixn Aug 07 '21 at 21:30
  • The issue I wanted to solve was that in the event of a 404, I could catch the error and instead return different code. In my case, I can't catch 404 at all. – clerkvector112 Aug 07 '21 at 22:40
  • Do you only want to use frontend code or do you also use Backend code, because if you do use a backend this would be so much easier, because cors is just a header and if you do the http request on the backend, you could just ignore the cors and just check the statuscode and send that back to the frontend. – fabian Aug 07 '21 at 23:05

1 Answers1

0

Since it is not possible to distinguish a CORS-Error from any other Error, let's say Network-Error, and you can't even read the Status-Code, so you can't tell if the website sent a 404 or any other code, the approach you want to go (checking it on the front-end) is technically impossible. CORS was specifically designed to behave that way. If you want to read more on that: Trying to use fetch and pass in mode: no-cors

Your best bet here would be to do this sort of thing on the backend, since you can just ignore the cors header and just read the data. You could do something like that:

I used express and axios, but you can use whatever you want to.

const express = require("express");
const app = express();
const axios = require("axios");

app.use(express.json());

app.post("/checkStatusCode", async (req, res) => {
  const { url } = req.body;
  if (url == undefined || typeof url != "string") {
    return res.status(400).json({ status: 400, msg: "URL required" });
  }
  try {
    const request = await axios.get(url);
    res.status(request.status).json({ url, status: request.status, msg: request.statusText });
  } catch (err) {
    if (err.response != undefined) {
      res.status(err.response.status).json({ url, status: err.response.status, msg: err.response.statusText });
    } else {
      console.log(err);
      res.status(500).json({ status: 500, msg: "Internal Server Error" });
    }
  }
});

app.listen(5000);

Then you would just call that on your frontend, and check for the Statuscodes:

var myHeaders = new Headers();
myHeaders.append("Content-Type", "application/json");

var raw = JSON.stringify({
  "url": "https://google.com"
});

var requestOptions = {
  method: 'POST',
  headers: myHeaders,
  body: raw,
  redirect: 'follow'
};

fetch("http://localhost:5000/checkStatusCode", requestOptions)
  .then(response => response.json())
  .then(result => console.log(result))
  .catch(error => console.log('error', error));

If you have trouble with CORS on your backend, there is a npm package for that: https://www.npmjs.com/package/cors

Just require and use it like this:

const cors = require("cors");
app.use(cors());
fabian
  • 268
  • 3
  • 15