Making Cross-Domain Requests with Axios Using JSONP in Vue
JSONP (JSON with Padding) enables cross-origin data retrieval by injecting a <script> tag whose source points to a remote endpoint returning executable JavaScript. Unlike standard XHR, it bypasses same-origin restrictions by exploiting how browsers load external scripts.
Cross-domain request flow using JSONP:
- Cliant dynamically creates a
<script>element targeting a URL with a query parmaeter specifying a callback function name. - Server wraps the result data in a call to that function and returns it as JavaScript.
- Browser executes the script, invoking the globally defined function with the data payload.
Axios does not provide built-in JSONP support, so extending it requires implementing the mechanism manually within a Vue component.
Install Axios if not already available:
npm install axios
Define a custom JSONP method on the Axios instance inside your Vue component:
import ax from 'axios';
ax.jsonpFetch = function (targetUrl) {
return new Promise((onSuccess, onError) => {
const cbId = 'cb_' + Math.random().toString(36).slice(2);
window[cbId] = onSuccess;
const separator = targetUrl.includes('?') ? '&' : '?';
const fullUrl = `${targetUrl}${separator}callback=${cbId}`;
const spt = document.createElement('script');
spt.src = fullUrl;
spt.async = true;
spt.onerror = () => {
cleanup();
onError(new Error('Script load failed'));
};
const cleanup = () => {
delete window[cbId];
document.head.removeChild(spt);
};
spt.onload = cleanup;
document.head.appendChild(spt);
});
};
// Usage example
ax.jsonpFetch('https://api.example.com/data')
.then(data => {
console.log('Received via JSONP:', data);
})
.catch(err => {
console.error('JSONP error:', err);
});
Key implementation notes:
- A unique callback identifier is generated per invocation to avoid collisions.
- The callback is temporarily attached to the global
windowobject so the server can invoke it. - Query string construction ensures proper placement of the
callbackparameter. - The
<script>tag is appended to<head>for asynchronous loading. - Cleanup removes both the DOM node and the global callback to prevent memory leaks.
- Error handling captures network failures during script retrieval.