Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Suppress console errors with XMLHttpRequest [duplicate]

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!

like image 293
Harold Avatar asked Apr 28 '14 17:04

Harold


1 Answers

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.

like image 93
Bergi Avatar answered Oct 13 '22 13:10

Bergi