RSS

Tag Archives: jsonp

Express.js and jsonp

Express.js has a very good jsonp handler, the key is to use it in the right way =)

The first step is to ensure the callback name. The default value is “callback” so on a res.jsonp(..) the server will look for req.query[“callback”] to build the response.
This value can be overridden with an app.set(‘jsonp callback name’,..).

app.js:

app.get('/', function(req, res) {
  var jsonp_callback = app.get('jsonp callback name');
  var jsonp = (req.query[jsonp_callback]);
  var result = [{},{},.....];
  if (jsonp) res.jsonp(result);
  else res.json(result);
});

jQuery

When asking for jsonp stuff, jQuery will handle the whole request/response stuff.
We just need to say the dataType and the callback key.

Here’s an example of the client side call:

$.ajax({
  url: "http://localhost:3000/",
  jsonp: "callback",
  dataType: "jsonp",
  success: function( response ) {
    console.log( response );
  },
  error: function(XHR, textStatus, errorThrown) {
    console.log(XHR);
    console.log(textStatus);
    console.log(errorThrown);
  }
});

AngularJS

Angular will expect the callback will be named “JSON_CALLBACK” so we have to use it this way:

$http.jsonp('http://localhost:3000?callback=JSON_CALLBACK')
  .success(function(data, status, headers, config) {
    console.log( data );
  })
  .error(function(data, status, headers, config) {
    console.log(data);
    console.log(status);
  });
 
Leave a comment

Posted by on 2015/02/04 in dev

 

Tags: , , , ,