Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save micjamking/0da1894ad63d2c992cf0 to your computer and use it in GitHub Desktop.
Save micjamking/0da1894ad63d2c992cf0 to your computer and use it in GitHub Desktop.
/**
* Copyright (c) 2015 Matthew Zipay <[email protected]>. All rights reserved.
* Licensed under the MIT License <http://opensource.org/licenses/MIT>.
*
* 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