0

I tried the answers in the suggested possible duplicate question but they didn't change the result.

I've been trying to POST to a remote server's API by ajax from a client on a local PC (testing Chrome and IE), with no success. Ajax returns an error with status 0 and the server returns 401. Without basic authentication, I confirmed that it worked. But with basic authentication, it never worked.

Client:

$.ajax({
    type : 'POST',
    url : 'http://api-url',
    data : data,
    success : function (response) {
        console.log(response);
    },
    error : function (xhr, status, error) {
        console.log(xhr);
        console.log(status);
        console.log(error);
    },
    beforeSend : function (xhr) {
        xhr.setRequestHeader('Authorization', 'Basic base64username:password');
    },
    xhrFields : {
        withCredentials : true
    }

Server:

<?php
    header('Access-Control-Allow-Origin: http://localhost');
    header('Access-Control-Allow-Credentials: true');
    header('Access-Control-Allow-Methods: GET, PUT, POST, DELETE, HEAD, OPTIONS');
    header('Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept, Authorization');
    echo "ok";

Could anyone suggest what I might be missing. I spent a day for it but couldn't find any working solution.

The server is CentOS 6.7 and Apache 2.2.15.

mmrn
  • 249
  • 2
  • 8
  • 18

1 Answers1

-1

If your remote server setting for Access-Control-Allow-Origin is just set to localhost then it will only work for local requests. Try:

header('Access-Control-Allow-Origin:*);
Dunski
  • 653
  • 5
  • 14
  • I think I have already tried that (and didn't work), but I will try it later anyway. – mmrn Jan 26 '16 at 23:59