16

Trying to use a pure JS approach to check if I have a valid JS image url. I am getting a warning that XMLHttpRequest is deprecated. What is a better way to do this?

urlExists(url) {
    const http = new XMLHttpRequest();
    http.open('HEAD', url, false);
    http.send();
    if (http.status !== 404) {
      return true;
    }
    return false;
  }
4

4 Answers 4

18

You're probably getting a message that the synchronous use of XMLHttpRequest is deprecated (because of its harmful effect on the user experience; it freezes the page while waiting for a response). I can assure you that proper asynchronous use of that API is not deprecated whatsoever.

Here's some example code for the correct use:

var xhr = new XMLHttpRequest()
xhr.onreadystatechange = function() {
    if (this.readyState === this.DONE) {
        console.log(this.status) // do something; the request has completed
    }
}
xhr.open("HEAD", "http://example.com") // replace with URL of your choosing
xhr.send()

Sign up to request clarification or add additional context in comments.

Comments

3

The cause of the warning was that in http.open('HEAD', url, false); you put a third argument (async) as false. As per the https://xhr.spec.whatwg.org/#synchronous-flag it should be set to true.

Comments

2

The warning is probably because you are tyring to do a synchronous request.

Comments

-2

XMLHttpRequest is deprecated, because the Fetch API replaced its place since 2015. Officially deprecated in 2023.

await fetch(url, {
    method: "POST", // GET, POST, PUT, DELETE
    mode: "cors", // no-cors, cors, same-origin
    cache: "no-cache", // default, no-cache, reload, force-cache, only-if-cached
    credentials: "same-origin", // include, same-origin, omit
    headers: {
      "Content-Type": "application/json",
      // 'Content-Type': 'application/x-www-form-urlencoded',
    }, extra options);

https://developer.mozilla.org/en/docs/Web/API/Fetch_API/Using_Fetch If something is deprecated, mozilla is way find replacement specifically for HTTP Related areas.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.