Last active
May 19, 2021 09:34
-
-
Save mzipay/69b8e12ad300ecaa467a to your computer and use it in GitHub Desktop.
AngularJS HTTP interceptor to work around CORS/JSONP problems
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* @license CC0 1.0 (http://creativecommons.org/publicdomain/zero/1.0/) | |
* | |
* The problem: | |
* You need to make a cross-domain request for JSON data, but the remote | |
* server doesn't send the necessary CORS headers, and it only supports | |
* simple JSON-over-HTTP GET requests (no JSONP support). | |
* | |
* One possible solution: | |
* Use 'jsonp-proxy-request-interceptor' to proxy the request through | |
* https://jsonp.afeld.me/. | |
* | |
* Much thanks to Aidan Feldman for an awesome service! | |
* <https://github.com/afeld/jsonp> | |
* <https://jsonp.afeld.me/> | |
*/ | |
var app = angular.module('jsonp-proxy-request-interceptor', []); | |
// (1) define a request interceptor | |
app.service('jsonpProxyRequestInterceptor', | |
function JsonpProxyRequestInterceptor($log) { | |
// (2) define a RegEx to extract raw JSON from the proxy response | |
var callbackRx = /callback\((.+)\);/gm; | |
this.request = function(config) { | |
// (3) check if this is a request that needs to be proxied | |
if (config.url === 'https://api.domain.com/' && config.method === 'GET') { | |
// (4) save the API URL, and set request URL to 'https://jsonp.afeld.me/' | |
var apiUrl = config.url; | |
config.url = 'https://jsonp.afeld.me/'; | |
// (5) set the url= and callback= params for https://jsonp.afeld.me/ | |
config.params = angular.extend({}, config.params || {}, { | |
url: apiUrl, | |
callback: 'callback' | |
}); | |
// (6) extract the raw JSON from the proxy response | |
config.transformResponse.unshift(function(data, headers) { | |
var matched = callbackRx.exec(data); | |
// (7) pass the raw JSON along to the next transformer | |
return matched ? matched[1] : data; | |
}); | |
} | |
// (8) return the (possibly modified) config | |
return config; | |
}; | |
}); | |
// (9) install the interceptor | |
app.config(['$httpProvider', function configHttp($httpProvider) { | |
$httpProvider.interceptors.push('jsonpProxyRequestInterceptor'); | |
}]); | |
// (10) stop banging your head against the wall |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment