6

I am trying to reach some RESTful services that are running under Apache preemtive basic authentication. I am using jquery Ajax, and sending the user and password with the 'Authentication' header. However, my request is throwing an empty error every time it runs.

Here is the full $.ajax call:

$.ajax({
      cache:false,
      url: urladdress,
      type:'GET',
      async:false,
      headers: { "cache-control": "no-cache" },
      dataType: "html", //or xml or json
      contentType: "html",
       beforeSend : function(req) 
       {
          req.setRequestHeader('Authorization', "Basic " +  base64string); //user:password);
       },
      success: function(data){
         successcallback(data);
      },
      error: function(xhRequest, ErrorText, thrownError){
           alert("ERROR: "+ JSON.stringify(xhRequest));
      },
      complete: function(result){
        ...
      }
});

What I am doing wrong? Is there something that I am ignoring here? Thanks.

Gabriel Mendez
  • 1,115
  • 1
  • 9
  • 28
  • Update: I changed the $ajax parameters. Now I am passing my credentials with username: and password: arguments. The error says: "Access to restricted URI denied" Sounds like a cross-domain problem, no? – Gabriel Mendez Apr 23 '13 at 18:20
  • Yes it's a cross-domain problem if you get "Access to restricted URI denied". You need to use JSONP for this – Kenny Ki Apr 24 '13 at 02:56
  • Sadly, I think I am going to use a PHP proxy for calling the services. It seems there is not any way to cross that with simple JavaScript. – Gabriel Mendez Apr 24 '13 at 18:53
  • If you don't own the service (cannot apply ?callback=) then a proxy is your best bet ;-) – Kenny Ki Apr 25 '13 at 03:39
  • credentials are not passed as a header in ajax. not sure how jquery is wired to handle how TO do it, but refer to http://www.w3.org/TR/XMLHttpRequest/#the-open()-method for info on using plain JS's xmlHttpRequest - the seldom-used fourth and fifth arguments to open()... – dandavis Apr 30 '13 at 23:04
  • @dandavis: You are right. I realized too late, but it is true. – Gabriel Mendez May 06 '13 at 18:22

1 Answers1

1

The solution is on the server-side, you must include some custom headers in response to cross domain works. Experiment send the following headers in response:

Access-Control-Allow-Origin: yourApiDomain

Access-Control-Allow-Methods: *

  • In case of using custom headers:

    Access-Control-Expose-Headers: X-My-Custom-Header, X-Another-Custom-Header

    Access-Control-Allow-Headers: X-My-Custom-Header, X-Another-Custom-Header

  • In case of using HTTP Cookies and HTTP Authentication information:

    Access-Control-Allow-Credentials: true

For more informations read the documentation in MDN about CORS:

rodmucha
  • 36
  • 2