Fading Coder

One Final Commit for the Last Sprint

Home > Tools > Content

Making Cross-Domain Requests with Axios Using JSONP in Vue

Tools 1

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:

  1. Cliant dynamically creates a <script> element targeting a URL with a query parmaeter specifying a callback function name.
  2. Server wraps the result data in a call to that function and returns it as JavaScript.
  3. 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 window object so the server can invoke it.
  • Query string construction ensures proper placement of the callback parameter.
  • 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.

Related Articles

Efficient Usage of HTTP Client in IntelliJ IDEA

IntelliJ IDEA incorporates a versatile HTTP client tool, enabling developres to interact with RESTful services and APIs effectively with in the editor. This functionality streamlines workflows, replac...

Installing CocoaPods on macOS Catalina (10.15) Using a User-Managed Ruby

System Ruby on macOS 10.15 frequently fails to build native gems required by CocoaPods (for example, ffi), leading to errors like: ERROR: Failed to build gem native extension checking for ffi.h... no...

Resolve PhpStorm "Interpreter is not specified or invalid" on WAMP (Windows)

Symptom PhpStorm displays: "Interpreter is not specified or invalid. Press ‘Fix’ to edit your project configuration." This occurs when the IDE cannot locate a valid PHP CLI executable or when the debu...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.