unexpected token : from angular $http.jsonp request to Instagram API - json

I'm making a request to an authorized Instagram account to display images on a site. Originally, I was running into No 'Access-Control-Allow-Origin' when using Angular's $http.get(....
From Matt's answer in this question, It seems that I can use getJSON, or Angular $http.jsonp, to bypass this issue. That Guy's answer also says "JSONP is really a simply trick to overcome XMLHttpRequest same domain policy".
So, I'm no longer getting that problem, and am getting a json payload:
{"pagination":{"next_url":"https:\/\/api.instagram.com... etc
But am getting a very ambiguous error:
Uncaught SyntaxError: Unexpected token :
This is a response from the Instagram API, so I'm not sure why there'd be a syntax error on the inbound json. Also, It's hard to locate the error since the jsonp response is all on a single line... where the error is reported.
The preview shows that I'm getting a full payload:

I found the issue. Unfortunately there are no JavaScript libraries to help with this, but in the Instagram API docs, for JSONP you can wrap the response with a callback so that the json payload will be wrapped in <script> tags (more info on jsonp here), therefore not blocked by Access Control Allow Origin.
https://api.instagram.com/v1/tags/coffee/media/recent?access_token=ACCESS-TOKEN&callback=callbackFunction
Response:
callbackFunction({
...
});
So, in your http request URI, you add in a callback parameter. Since I am using Angular, their docs for $http.jsonp() requests specify the callback string as "JSON_CALLBACK".
So, my request URL for Angular would be:
$http.jsonp(
'https://api.instagram.com/v1/tags/coffee/media/recent?
access_token=ACCESS-TOKEN&callback=JSON_CALLBACK')
.success(function(data) {...

Related

VM892:1 Uncaught SyntaxError: Unexpected token e in JSON at position 0

I'm presently working on a phx / phoenix API written in Elixir. And I have created a frontend for the API using React.js. However, I'm getting the below error message in the JS console of the browser.
I have successfully created a user using Postman, so I'm 99% sure the error isn't with the phx project, but rather somewhere with the React project.
I have both the frontend and backend hosted on github. And a .env file will need to be created in the root of the React project with the below line,
REACT_APP_API_URL=http://localhost:4000/api
and was working my way through the following tutorial.
Any and all help would greatly be appreciated.
The output of localStorage.getItem("token") being
eyJhbGciOiJIUzUxMiIsInR5cCI6IkpXVCJ9.eyJhdWQiOiJVc2VyOjEiLC‌​JleHAiOjE0ODcyODI4OD‌​csImlhdCI6MTQ4NDY5MD‌​g4NywiaXNzIjoiUGhvZW‌​5peENoYXQiLCJqdGkiOi‌​IwNzFlYzgwYi0wZmYzLT‌​QyYzgtODA3Mi1kNzViZm‌​VhZTg4NWEiLCJwZW0iOn‌​t9LCJzdWIiOiJVc2VyOj‌​EiLCJ0eXAiOiJhY2Nlc3‌​MifQ.NsuqH50HooK8vjF‌​fHtPH9iXSykZ9oYA0ul4‌​b_C5fQtpu_zFvNNy-skc‌​v9HI2i25X-NlB-9xOr-x‌​zh2abnrpYUw
suggests that for some reason, the app stored the token without passing it through JSON.stringify, and calling JSON.parse on this string throws the Unexpected token e error, as expected.
I did not see any localStorage.setItem without JSON.stringify in the current code, so the token was probably stored like that in a previous version of the app. You should try clearing it manually and logging in again.
When we get the non-JSON response, we get such error..
To avoid such error, mention the responseType: Text in your api endpoint call.
This will work,
return this.http.post(`${environment.apiUrl}/login`, user, {responseType: 'text'});
This will not work(If you mention type),
return this.http.post<string>(`${environment.apiUrl}/login`, user, {responseType: 'text'});
This error message usually means you're getting a non-JSON response. If you look at the raw response in the Network tab of your debugger, you should be able to see what you're getting back from the server.

Google OAuth - Incorrect JSON while Validating Access Token

I'm getting an access token from the Android SDK which I'm sending to the server. On the server side, I'm calling the following API to validate my token:
https://www.googleapis.com/oauth2/v1/tokeninfo?access_token=<token here>
From Google, I'm getting the following response (partial response added):
{\"statusCode\":200,\"body\":\"{n \"issued_to\":
\"407408718192.apps.googleusercontent.com\",n \"audience\":
\"407408718192.apps.googleusercontent.com\",n \"user_id\":
\"110586055381870434283\",n \"scope\":
\"https://www.googleapis.com/auth/plus.login
https://www.googleapis.com/auth/plus.me"}
Unfortunately, this JSON is not parseable because of the backslashes & i'm not able to validate the token identity.
Is this a problem with the Google API or do I need to apply any regex?
Google sends back proper JSON without the slashes, being exactly the part that's inside the "body" element of the output that you paste (well without the slashes).
So your Node.js HTTP client is wrapping it with the HTTP status code element and puts in the slashes as well, so your clients need convert back from that on its own.

Not able to fetch the json response through angularjs

Need to fetch the build values from apache.org. So i am using their api
https://builds.apache.org/api/json
I tried angularjs $http.jsonp but not able to fetch the data.
In chrome console under network json api is getting loaded but the data is not getting returned instead it is throwing the response as error.
app.controller("jsoncontroller",function($scope,$http){
var url='https://builds.apache.org/api/json';
$http.jsonp(url).success(function(data){
console.log('success');
})
.error(function () {
console.log('error')
});
});
Getting the error as
Uncaught SyntaxError: Unexpected token :
error
As per the jsonp angular docs, you must append JSON_CALLBACK to the URL: https://builds.apache.org/api/json?jsonp=JSON_CALLBACK
However, that URL doesn't work because even when the callback parameter is specified, the server still sends back a content-type of application/json, instead of the expected application/javascript. This causes it to be parsed (evidently) by the json parser instead of the javascript callback needed for JSONP to work. I'm not versed enough in JSONP or Angular to know who is it fault here.
I've made a fiddle with this working with another URL.
[Update]: The apache build server appears to use Jenkins, which has disable JSONP from the remote API. You can verify this yourself by trying to hit their jsonp endpoint, which returns a 403. You'll have to use another endpoint, no way I can see around this.

Detect malformed/invalid JSON in an AngularJS $http.post() call

As can be seen in AngularJS's source, any $http.post request that returns an HTTP code in the 200-299 range will trigger the success() callback even if the response contains invalid data (like for example invalid JSON).
I'm specifically setting my call's responseType: 'json' and even then the success callback is fired when something else comes back. This is especially annoying in the development server where PHP's display_errors setting is turned on. When something goes wrong server-side and PHP outputs an error message the AngularJS app doesn't detect this and continues happily.
Is there a way to prevent this? I mean, to make the AngularJS app fire the error() callback when the response data is invalid JSON?
Thanks
so your PHP server responds with a 200 error code even on an error? Not knowing PHP, this feels like a server configuration problem to me. I'd expect a 500 error with a payload. That being said, there are two things that I can think of offhand.
$http includes transformResponse handlers you can set up to inspect the response for problems.
$http also includes the concept of "interceptors" which allow you to pick up the response payload and do something with it. You could use an interceptor to "reject" the response.
More information on transformResponse and "interceptors" in the $http documentation:
http://docs.angularjs.org/api/ng.$http

Getting `Unexpected token :` in angularjs but cannot use callback

I'm trying to query the Spotify Metadata API with AngularJS but I keep running into the following error.
Uncaught SyntaxError: Unexpected token :
Now I know typically when querying you should add callback=JSON_CALLBACK as a query string but in this case it won't work. It returns:
Failed to load resource: the server responded with a status of 400 (Bad Request)
I am using $http.jsonp().
Example without callback | Example with callback
So, is there a way around this using pure Javascript or I'm best add a server-side wrapper (which I've got working but rather if it was pure Javascript)?
It doesn't seem like Spotify is providing jsonp support, but they do support CORS - so this should work:
function spotify_api($http) {
var url = "http://ws.spotify.com/lookup/1/.json?uri=spotify:track:5PJSqY8jbYzr4a6dl5Ory1";
//CORS support
delete $http.defaults.headers.common['X-Requested-With'];
$http.get(url).success(function(data) {
console.log(data);
});
}
See my update: http://jsfiddle.net/69kYH/
The bad news is that CORS doesn't seem to work properly in angular with older versions of IE - see AngularJS - Calling Flickr API fails with warning message