9

I'm trying to write a "fileExists" function in Javascript which simply sends a request to the server and returns false if a 404 status is sent back.

The function works perfectly, but I can't seem to suppress the error message I get in the Google Chrome console stating: GET /something/foobar 404 (Not Found).

Does anyone know a way to work around this?

For reference, here's the code I'm using:

    var fileExists = function(url) {
        var req = new XMLHttpRequest();
        req.open('GET', url, false);
        req.send();
        return req.status === 200;
    };

Thanks in advance!

Bergi
  • 630,263
  • 148
  • 957
  • 1,375
Harold
  • 1,372
  • 1
  • 14
  • 25

1 Answers1

6

I don't think there's a way to prevent the console from stating that loading a ressource failed. There's nothing wrong with that actually.

You might however better use a HEAD request instead of really loading the ressource with GET. Try

function fileExists(url) {
    var req = new XMLHttpRequest();
    req.open('HEAD', url, false);
    req.send();
    return req.status !== 404;
}

If you really want to avoid 404 statuses, install a service on your server that you can query whether a file/path is available. It would always return the XML/JSON/textual response with a 200 OK status, regardless of that contains true or false.

Trevor
  • 13,085
  • 13
  • 76
  • 99
Bergi
  • 630,263
  • 148
  • 957
  • 1,375
  • 2
    Thanks, I was afraid of that. However, I've already tried all methods (even PUT and DELETE :p) all give the same result though :( – Harold Apr 28 '14 at 17:47
  • 3
    Actually this solution does not work. Actually the error on console seems worse in this way. – Felipe Oct 21 '15 at 13:28
  • 1
    Yes there is something wrong actually. The OP and I would like the error message to go away because no error has occurred. – DavidWalley Jul 04 '17 at 19:35
  • @DavidWalley 404 *is* an HTTP error. If you don't want to get logs from them in the console, disable the logging - see [the duplicate about Chrome devtools](https://stackoverflow.com/q/4500741/1048572) and [here for Firebug](https://stackoverflow.com/a/13838722/1048572) – Bergi Jul 04 '17 at 20:54