This post explains how developers can circumvent the Same Origin Policy implemented by all modern web-browsers by requesting data in the JSONP format. Generally modern browsers do not allow POST, PUT or PATCH request if the request is not done by same origin. By using JSONP we can easily overcome this. But lets learn some basics.

What is Same Origin Policy?

The Same Origin Policy is a security measure imposed by all modern browsers that restricts the ability of JavaScript to make AJAX requests across domains. As a security measure this is desirable because it makes it more difficult for malicious scripts to communicate with domains you don’t trust. However, it also makes it harder for developers to write client side apps that use JavaScript to communicate with REST API. For a more detailed explanation of the Same Origin Policy see
http://en.wikipedia.org/wiki/Same-origin_policy

JSONP

JSONP, or JavaScript Object Notation with Padding, is a technique for returning data in a way that works around the restrictions imposed by the Same Origin Policy. It relies on the fact that tags are not subject to the Same Origin Policy. When data is requested using JSONP it is returned as a text representation of a JSON object wrapped or “padded” with a JavaScript function name.
When a tag processes a JSONP response, the JSON object is treated as an argument and if the function is already defined on the page it is executed immediately, giving that function access to the JSON object.

Lots of chit chat lets make hands dirty

JSONP in JS

//jsonp.js
var JSONP = (function(){  
  var that = {};

  that.send = function(src, options) {
    var callback_name = options.callbackName || 'callback',
      on_success = options.onSuccess || function(){},
      on_timeout = options.onTimeout || function(){},
      timeout = options.timeout || 10;

    var timeout_trigger = window.setTimeout(function(){
      window[callback_name] = function(){};
      on_timeout();
    }, timeout * 1000);

    window[callback_name] = function(data){
      window.clearTimeout(timeout_trigger);
      on_success(data);
    };

    var script = document.createElement('script');
    script.type = 'text/javascript';
    script.async = true;
    script.src = src;

    document.getElementsByTagName('head')[0].appendChild(script);
  };

  return that;
})();

//In your HTML script tag or in JS file 
JSONP.send('/your/endpoint?callback=name', { callbackName: 'name' });  

and In your Express App just call

//route.js
route.post('/your/endpoint',function(req, res){  
    res.jsonp('your response object')
});

You may need CORS module

Not joking!!! really so simple in ExpressJS

© 2016. All Rights Reserved.

Proudly published with Ghost