JSONP- A beginner's guide

Jan 17
23:49

2021

Srishti Singh

Srishti Singh

  • Share this article on Facebook
  • Share this article on Twitter
  • Share this article on Linkedin

JSON Processing (JSON-P) is a Java API for processing JSON messages (for example, parsing, generating, transforming and querying). It generates and consumes streaming JSON text (like the StAX API for XML) and allows the development of a Java object model for JSON text using API classes (similar to DOM API for XML).

mediaimage

JSONP is a way to load 3rd party server data,JSONP- A beginner's guide Articles bypassing the policy of the same root. You should not load a JSON file from a domain and port that is not the current one by default and use it in your application. Or you may want to access any JSON-served publicly accessible API in the browser.

This is a common need to use APIs, but we are limited to the browser for security reasons.This conduct must be rejected by default to avoid future complications due to the Same-Origin Policy.

Before CORS existed, JSONP was born. Today, CORS is a more sensible solution to the problem (the only one?), but it is also helpful to know JSONP, which may be easier in your situation. Some security problems have also been found around JSONP since its inception, therefore you should be aware of all the security implications of using JSNOP.

How JSONP works?
Let’s create a function called jsonp that will send the request in the JSONP fashion.

let jsonpID = 0;

function jsonp(url, timeout = 7500) {
const head = document.querySelector('head');
jsonpID += 1;

return new Promise((resolve, reject) => {
let script = document.createElement('script');
const callbackName = jsonpCallback${jsonpID};

script.src = encodeURI(${url}?callback=${callbackName});
script.async = true;

const timeoutId = window.setTimeout(() => {
cleanUp();

return reject(new Error('Timeout'));
}, timeout);

window[callbackName] = data => {
cleanUp();

return resolve(data);
};

script.addEventListener('error', error => {
cleanUp();

return reject(error);
});

function cleanUp() {
window[callbackName] = undefined;
head.removeChild(script);
window.clearTimeout(timeoutId);
script = null;
}


head.appendChild(script);
});
}


As you can see, there’s a shared variable called jsonpID — it will be used to make sure that each request has its own unique function name.

Article "tagged" as:

Categories: