Axios JSONP Extension
axios-jsonp-pro is a plugin that extends the popular Axios HTTP client, adding JSONP (JSON with Padding) request capabilities for web browsers and Node.js environments. While Axios itself is a robust, promise-based client for standard HTTP requests, it does not natively support JSONP, which is often used for cross-domain data fetching from older APIs. This package seamlessly integrates by patching the global Axios instance, allowing developers to make JSONP requests using `axios.jsonp()`. Currently at version 1.1.8, the project appears to be in maintenance mode, with its last publish date being several years ago, though it still functions as a reliable solution for JSONP needs within an Axios-powered application. Its key differentiator is providing a familiar Axios-like API for JSONP, contrasting with standalone JSONP libraries or direct `<script>` tag injection.
Common errors
-
ReferenceError: axios is not defined (when calling axios.jsonp)
cause `axios-jsonp-pro` was imported before `axios`, or `axios` was not installed/imported at all.fixEnsure `axios` is installed (`npm install axios`) and imported or required before `axios-jsonp-pro`. The import order should be `import axios from 'axios'; import 'axios-jsonp-pro';`. -
JSONP request timeout
cause The JSONP server did not respond within the default or specified timeout period, or the callback function was not invoked by the server's response.fixIncrease the `timeout` option in your `axios.jsonp()` call. Verify the JSONP endpoint is active and correctly configured to return data within a reasonable timeframe. Check network connectivity and server logs. The default timeout might be too aggressive for slower networks or servers. -
Uncaught SyntaxError: Unexpected token ':' (or other parsing errors in browser console after JSONP request)
cause The server responded with invalid JSONP, or plain JSON/HTML instead of wrapping the data in the expected callback function. This can also happen if the `callbackParamName` or `callbackFunctionName` is mismatched.fixInspect the network response to confirm it's valid JSONP (e.g., `myCallbackFunction({'data': 'value'})`). Ensure the `callbackParamName` in your `axios.jsonp()` configuration matches what the server expects (default is `callback`). If the server expects a specific callback function name, you might need to configure that within the request parameters.
Warnings
- gotcha This package extends the global `axios` instance. If you create multiple isolated Axios instances or rely on a specific `axios` object, ensure `axios-jsonp-pro` is imported and applied to the correct instance, or be aware of potential global side effects. It adds `jsonp` directly to `axios.default` if not using named imports.
- breaking The underlying `axios` package had critical supply chain compromises (versions `1.14.1` and `0.30.4`) that injected malware. While `axios-jsonp-pro` itself was not compromised, any project using these malicious Axios versions would be affected.
- gotcha JSONP requests are inherently less secure than standard CORS-enabled XHR or Fetch requests due to their reliance on injecting `<script>` tags, making them vulnerable to Cross-Site Scripting (XSS) if the JSONP endpoint is untrusted or improperly secured.
- deprecated JSONP is a legacy technique for cross-domain requests. Modern web development favors CORS (Cross-Origin Resource Sharing) or proxy servers for handling cross-domain communication due to better security and flexibility. JSONP should generally only be used when dealing with older APIs that do not support CORS.
Install
-
npm install axios-jsonp-pro -
yarn add axios-jsonp-pro -
pnpm add axios-jsonp-pro
Imports
- Axios global instance (patched)
import { jsonp } from 'axios-jsonp-pro'; // Incorrect, it patches the axios instanceimport axios from 'axios'; import 'axios-jsonp-pro'; // Now axios.jsonp is available axios.jsonp('/api/data') - CommonJS require
const jsonpAdapter = require('axios-jsonp-pro'); // jsonpAdapter is not directly usable as a functionconst axios = require('axios'); require('axios-jsonp-pro'); // Now axios.jsonp is available axios.jsonp('/api/data') - Axios instance with adapter (alternative, less common)
axios({ url: '/jsonp', adapter: jsonpAdapter }); // Incorrect for axios-jsonp-pro, this pattern is for other jsonp adapters like 'axios-jsonp'. axios-jsonp-pro patches the instance directly.import axios from 'axios'; import jsonpAdapter from 'axios-jsonp-pro'; const instance = axios.create({ adapter: jsonpAdapter }); instance.jsonp('/api/data'); // May not be directly exposed this way, prefer global patch if available.
Quickstart
import axios from 'axios';
import 'axios-jsonp-pro'; // This patches the axios instance
async function fetchUserData(userId) {
try {
// Basic JSONP request
const response1 = await axios.jsonp(`/user?ID=${userId}`);
console.log('User data (basic):', response1.data);
// JSONP request with custom options, e.g., timeout
const response2 = await axios.jsonp('/user', {
timeout: 5000, // 5 seconds timeout
params: {
ID: userId,
callback: 'myJsonpCallback' // Specify custom callback parameter name if needed
}
});
console.log('User data (with options):', response2.data);
} catch (error) {
if (axios.isCancel(error)) {
console.log('Request canceled', error.message);
} else {
console.error('JSONP request failed:', error);
}
}
}
// Example usage (replace with your actual JSONP endpoint)
fetchUserData(12345);
// Note: This code will only work if a server is configured to respond with JSONP to /user and ID parameter.