-2

I am building an AngularJS web app and at the moment I am creating a form to allow the user to link to youtube videos. I have a thumbnail associated with youtube videos and when the user enters a youtube link, i fetch the image from https://img.youtube.com/vi/${videoId}/maxresdefault.jpg

That goes into this:

<img src="{{element.video.thumb}}>

So, my current solution is:

element.video.thumb = `https://img.youtube.com/vi/${videoId}/maxresdefault.jpg`

My problem is that not all youtube videos have their thumbnail available at that link. I want to be able to identify if a video has it available or not. I notice that I get a 404 response in my console when a thumbnail is not available. So I tried to check if the thumbnail exists using $http service. I tried both variants below:

$http.get(`https://img.youtube.com/vi/${videoId}/maxresdefault.jpg`)
$http.jsonp(`https://img.youtube.com/vi/${videoId}/maxresdefault.jpg`,{jsonpCallbackparam: "callback"})

The first one gives me a CORS error, and the second one doesn't work because the MIME type of the response is image/jpeg and it gives error when trying to execute the callback.

My first question is:

Why assigning the link to the src attribute of an img fetches the resource with no issues, but trying to access the resource with ah HTTP request gives a CORS error?

My second question is:

How can I execute some code if I get a 404 response after assigning the img src attribute?

sideshowbarker
  • 81,827
  • 26
  • 193
  • 197
SirWinning
  • 111
  • 8

2 Answers2

0

About your second Question (and the title of this Question) the solution should be to use the Error Event. Use .addEventListener() to add the required EventListener.

user103675
  • 15
  • 4
  • The event is [*`Error`*](https://developer.mozilla.org/en-US/docs/Web/API/ErrorEvent) not *`onerror`*. *onerror* is the name of the HTML attribute that configures the handler. But, **[inline HTML event handlers should not be used](https://stackoverflow.com/questions/43459890/javascript-function-doesnt-work-when-link-is-clicked/43459991#43459991)** - - `.addEventListener()` is the modern standard. Also, W3 Schools is widely known to have incomplete, out of date or flat out wrong information. Use the Mozilla Developer's Network instead. – Scott Marcus May 11 '18 at 14:47
  • Thanks for this it's very useful! – SirWinning May 11 '18 at 14:53
0

An XMLHttpRequest is being used in the .get to set the image from the browser, so a CORS error is triggered.

In your request you need to ask the target server for permission, using a crossOrigin attribute.

You can see: https://www.html5rocks.com/en/tutorials/cors/

L0uis
  • 703
  • 5
  • 8