AngularJS resource service with jsonp fails-Collection of common programming errors

I struggled a lot with this problem, so hopefully this will help someone in the future 🙂

JSONP expects a function callback, a common mistake is to call a URL that returns JSON and you get a Uncaught SyntaxError: Unexpected token : error. Instead, JSONP should return something like this (don’t get hung up on the function name in the example):

angular.callbacks._0({"id":4,"name":"Joe"})

The documentation tells you to pass JSON_CALLBACK on the URL for a reason. That will get replaced with the callback function name to handle the return. Each JSONP request is assigned a callback function, so if you do multiple requests they may be handled by angular.callbacks._1, angular.callbacks._2 and so forth.

With that in mind, your request should be something like this:

var url = 'http://myserver.com:8888/dosomething/[email protected]/arg2';
$http.jsonp(url + '?callback=JSON_CALLBACK')
   .then(function (response) {
       $scope.mydata = response.data;
       ...

Then AngularJS will actually request (replacing JSON_CALLBACK):

http://myserver.com:8888/dosomething/[email protected]/arg2?callback=angular.callbacks._0

Some frameworks have support for JSONP, but if your api doesn’t do it automatically, you can get the callback name from the querystring to encapsulate the json. Example is in Node.js:

var request = require('request');
var express = require('express');
var app = express();

app.get('/', function(req, res){
    // do something to get the json
    var json = '{"id":4,"name":"Joe"}';

    res.writeHead(200, {"Content-Type": "application/javascript"});
    res.write(req.query.callback + '(' + json + ')');
    res.end();
});
app.listen(8888);