Making jQuery.ajax request through a proxy server
Asked Answered
L

3

10

I'm writing a Chrome extension. If you make jQuery.ajax request for a regular http page from within a page served via https, then the request is blocked by Chrome. I was wondering if I could fetch the requested page using a secure proxy.

So, is it possible to use a generic proxy server for some jQuery.ajax request? If so, how? Note, changing the proxy setting of the browser is not an option.

Linguistics answered 3/5, 2014 at 19:29 Comment(0)
S
1

Yes, it is.

What we did at work was implement a proxy that does exactly that:

  1. It takes web service calls from the same origin, then,
  2. on the server side, maps them to a web service of another origin,
  3. sends them there,
  4. receives the results and
  5. passes them on back to the caller.

This way you can both comply with the same origin policy and work with other origins. However, you will always need a server-side proxy functionality.

Structuralism answered 3/5, 2014 at 19:37 Comment(2)
Cross domain is not the issue. I'm looking for a way to route jQuery.ajax (or some javascript code) through a generic proxy server.Linguistics
Ahh ok, sorry for the misunderstanding.Structuralism
H
1

[And a year goes on...] If I understood your question correctly, you want to change your AJAX request depending on the webpage you are currently at. jQuery provides a number of AJAX related methods which might help you with this.

My suggestion is to use jQuery.ajaxPrefilter and adapt your query to use the proxy instead of the original host. An example from the documentation:

$.ajaxPrefilter(function( options ) {
  if ( options.crossDomain ) {
    options.url = "http://example.com/proxy/" + encodeURIComponent( options.url );
    options.crossDomain = false;
  }
});

To spice it up a little bit, you could also use any of the global AJAX event handlers to monitor your request. For example to see if any of the requests fail:

$( document ).ajaxError(function() {
 console.log("Somethin' went wrawng!");
});
Hong answered 9/7, 2015 at 9:43 Comment(0)
B
0

You would need an external library to perform Ajax requests via a HTTP Proxy using JQuery. Out-of-the-box, JQuery does not have this functionality. An example of such is https://www.AjaxProxy.com which can be used with your query as follows;

ajaxProxy.proxy.url = "http://your proxy";
ajaxProxy.proxy.credentials.username = "proxy username";
ajaxProxy.proxy.credentials.password = "proxy password";
$.ajax({
    type: "GET",
    url: "https://ICANHAZIP.COM",
    headers: ajaxProxy.proxyHeaders(),
    dataType: "text"
}).done (function (data) {
    console.log(data);
});
Breather answered 30/9, 2021 at 14:56 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.