[AngularJS] JSONP text/plain

Hi everybody,

I'm having a big change in my life these days this is why I wasn't this available to write Blog Posts but this didn't stop me working on my website.

I've added my portfolio using the Flickr API, you can have a look at it there. I thought it would be straightforward and be integrated in one hour max. The fact was that it costs me almost an entire day to integrate it... This is why I'm sharing my experiments with you.

So to put some context on this, I'm making my personal website using jekyll because of GitHub personal page hosting offering this option and angularjs for the easy to integrate philosophy. This is not a lot of libraries, this is why I need external services to collect informations to show on my website (I'm still waiting for a Blogger API if you read this Google hahaha).

Ok, then let's go back to the original problem, I figured that I had a Flickr showing my previous works (that I thought was lost in my laptop crash \o/), and I wanted to use the API to show it on my website.

First of all I initially intented to make a GET request to get my gallery data. This was not an option because of cross domain request limitation. I passed this issue rapidly by changing it to JSONP because cross domain request limitation do not apply for JSONP. Ok, we're getting to the point of this article, I wanted to share with you some JSONP specifics for you to understand why it allows us to make cross domain requests.

You probably know that javascript use the XMLHttpRequest for AJAX requests. This method limit the possible requests to the same domain as the webpage for security reasons. JSONP use a really simple trick to bypass this : in HTML you can include a javascript file from a remote domain using the script tag. So the idea is to include a javascript file making a call to a local callback function with the JSON in argument. To resume this I made a little diagram explaining it (sorry I only had paint available) :


Next I couldn't get API response to be parsed in object. Every single time I only got a string response. After a while making a lot of tests, I checked the webservice and I detected that response was encoded in mime-type text/plain. This was the answer, in angular, $resource don't parse well text/plain encoded data so I had to use the $http dependency to manually parse returned data. You can have a look to my website directives file and check the Flickr service for more infos.

I hope that this post will also help you to integrate easily bad mime-type encoded REST webservices and remember that everytime there is a solution. Have fun :)

Most seen