Make a summary every day, persistence is victory!
/** @date 2021-05-24 @description JSONP */Copy the code
One (sequence)
JSONP(JSON with Padding) is a cross-domain solution with good compatibility, but can only handle GET requests; The principle is to use THE SCRIPT tag of HTML to solve the cross domain limitation. A few points to note:
- The name of the front-end callback function needs to match the name of the back-end function, so it is best to pass in the function name of the front-end, and the back-end process based on this name.
- The back end returns a string, and the front end performs a callback after the data is returned.
- The callback needs to be bound to window because the script tag’s last scope is window;
Ii (Front-end Implementation)
const jsonpGet = (url, params, cbName, cb) => { const container = document.getElementsByTagName('head')[0]; const requestEle = document.createElement('script'); requestEle.src = `${url}? ${parmaFormatter(params)}&callback=${cbName}`; container.appendChild(requestEle); window[cbName] = function (data) { cb && cb(data); container.removeChild(requestEle); delete window[cbName]; }; requestEle.onerror = () => { window[cbName] = function () { cb && cb('has error'); }; container.removeChild(requestEle); delete window[cbName]; }; }; const parmaFormatter = (params) => { const keys = Object.keys(params); return keys.reduce((acc, cur, index) => { if (index === keys.length - 1) { return (acc += `${cur}=${params[cur]}`); } else { return (acc += `${cur}=${params[cur]}&`); }} "); };Copy the code
Three (use)
jsonpGet('http://localhost:3000', { a: 1, b: 2 }, 'jsonp_test', (res) => {
console.log(res);
});
Copy the code
Iv (Extended)
Implement the Promise version:
const jsonpGet = (url, params, cbName) => {
const container = document.getElementsByTagName('head')[0];
const requestEle = document.createElement('script');
requestEle.src = `${url}?${parmaFormatter(params)}&callback=${cbName}`;
container.appendChild(requestEle);
return new Promise((resolve, reject) => {
window[cbName] = function (data) {
resolve(data);
container.removeChild(requestEle);
delete window[cbName];
};
requestEle.onerror = () => {
window[cbName] = function () {
reject('has error');
};
container.removeChild(requestEle);
delete window[cbName];
};
});
};
jsonpGet('http://localhost:3000', { a: 1, b: 2 }, 'jsonp_test').then(
(res) => {
console.log(res);
}
);
Copy the code