0

I know questions about getting HTTP response status codes have already been asked a lot, but all the answers I've found are in jQuery. I would like this answer in pure JavaScript.

What is the simplest/best way in my script that I can receive a value for the HTTP response status code of a URL string, were the respective URL to be launched? I want my string to be checked to see if an HTTP request can be successfully completed with it.

JCollier
  • 1,102
  • 2
  • 19
  • 31
  • Does this answer your question? [Check if a JavaScript string is a URL](https://stackoverflow.com/questions/5717093/check-if-a-javascript-string-is-a-url) – CESCO Dec 13 '19 at 23:15
  • No. That question looks at the syntax of a string: I actually want my string to be checked to see if an HTTP request can be successfully completed with it. – JCollier Dec 13 '19 at 23:21
  • 3
    `let response = await fetch(theURL); console.log(response.status);` – Stephen P Dec 13 '19 at 23:31
  • 1
    Checking the validity of the URL and checking to see if an HTTP request can be made successfully are two different things. You can have a valid url such as `https://www.thisdomaindoesnotexistasitisjustanexample.com` but an HTTP request will fail as the domain does not exist (at the time of writing!) – Alexander Holsgrove Dec 13 '19 at 23:32
  • Alex: good point. I supposed I should have used a different word than 'valid', or at least explained better that valid meant 'currently working'. – JCollier Dec 13 '19 at 23:36
  • 1
    @StephenP you should post your answer. It tested it and it works for my situation. – JCollier Dec 13 '19 at 23:40
  • @StephenP suggestion works only if theUrl has the same origin or has CORS enabled. Else you a NetworkError (CORS) will be thrown. – Christian Rodemeyer May 28 '22 at 10:15

0 Answers0