0

I have this code:

var url2 = 'https://vechainstats.com/nft/vereapers/2576/';
var img = document.createElement('img');
img.src = url2;

The link doesn't exist. So, I get in the console:

Console

GET https://vechainstats.com/nft/vereapers/2576/ 404

How can I get this error message (404) in JavaScript?

Thank you


I've tried adding addEventListener('error') to img but the log doesn't show 404 error. I've tried try / catch. I've tried fetch (CORS & CORB problems).

codesnerd
  • 767
  • 2
  • 8
  • 23
pf420x
  • 1
  • 2
    Img error event? Using addEventListener – Jaromanda X Sep 09 '22 at 13:04
  • Why do you need the 404 specifically? Why is knowing that there has been an error not enough? Looks a bit like an [XY Problem](https://meta.stackexchange.com/q/66377). – Ivar Sep 09 '22 at 13:06
  • Does this help? [using onerror for 404 for src different then img](https://stackoverflow.com/questions/30968007/using-onerror-for-404-for-src-different-then-img) – evolutionxbox Sep 09 '22 at 13:09
  • Does this answer your question? [How can I catch a 404 error in Javascript?](https://stackoverflow.com/questions/45581361/how-can-i-catch-a-404-error-in-javascript) – Pete Sep 09 '22 at 13:12
  • @JaromandaX I've tried this but doesn't return the state... – pf420x Sep 09 '22 at 13:36
  • @Ivar I have to test the existence of urls, but when I do it with fetch method i have a Cors problems that i can't resolve, so I choose this 'img method' – pf420x Sep 09 '22 at 13:41
  • @evolutionxbox that didn't work here, i have a Corb error that i can't resolve... – pf420x Sep 09 '22 at 13:45
  • I doubt you can get the HTTP response status code from an image element. And it might be for the very same reason that CORS doesn't allow you to access it. It could reveal information that shouldn't be revealed. Your best bet is probably to make a call to your server and let the server make a call to that URL to decide if it exists. – Ivar Sep 09 '22 at 13:52
  • @Ivar doing this with ajax (php) ? or there is a javascript method ? – pf420x Sep 09 '22 at 13:55
  • Yes, making an AJAX call to PHP (if that is what you are running on the server) and then let PHP make the call to that URL to see if it exist. I don't think this is possible directly via client-side (the browser) JavaScript. – Ivar Sep 09 '22 at 13:58
  • @Ivar I really wanted to avoid this way but i'm now resigned.... Thanks a lot for your dispo. Bye – pf420x Sep 09 '22 at 14:12

0 Answers0