javascriptjqueryajaxcurlowncloud

perform an API call with Ajax instead of cUrl


I have a service running on the same domain of my website that expose an API. I have managed to call the API using cUrl but I'd like to move it to some vanilla js/jquery.

My actual code is:

$postData = array(
    'userid' => $userid,
    'password' => $password,
    'email' => $userid
);

//creo utente base
$ch = curl_init();

curl_setopt($ch,CURLOPT_URL, 'https://admin:password@xxx.com/cloud/ocs/v1.php/cloud/users');
curl_setopt($ch,CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch,CURLOPT_POST, 1);
curl_setopt($ch,CURLOPT_POSTFIELDS, http_build_query($postData));

I have tried with a simple ajax request like this:

$.ajax({
    url: 'https://admin:password@xxx.com/cloud/ocs/v1.php/cloud/users',
    method: 'post',
    data: {userid:'a',password:'b',email:'c'},
    dataType: 'json'
}).done(function(data){
    //handle the results
});

or this:

$.ajax({
        url: 'https://mydomain/cloud/ocs/v1.php/cloud/users',
        beforeSend: function (xhr) {
            xhr.setRequestHeader ("Authorization", "Basic "+btoa(admin:password));
        },
        method: 'post',
        data: {userid:'mario@mari.com',password:'Annapurna1',email:'mario@mari.com'},
        dataType: 'json'
    }).done(function(data){
        console.log(data);
    });
        

but i get a 401 error that is "unhautorized". this means that the credentials provided in the url are not valid. But if I make a post request with the same url using Postman it passes the authorization.

What am I missing here?


Solution

  • Actually the error I was getting was completely misleading.

    I solved by adding contentType: 'application/x-www-form-urlencoded', that is used to send the parameters to the API simulating a form. Adding this resolved the issue even if the error message was related to the wrong authentication (the username and the password used to log in) and not to the parameters passed to the API.

    So my final code is

    $.ajax({
            url: 'https://mydomain/cloud/ocs/v1.php/cloud/users',
            beforeSend: function (xhr) {
                xhr.setRequestHeader ("Authorization", "Basic "+btoa('admin:password'));
            },
            contentType: 'application/x-www-form-urlencoded',
            method: 'post',
            data: {userid:'john@gmail.com',password:'userpassword',email:'john@gmail.com'},
            dataType: 'json'
        }).done(function(data){
            console.log(data);
        });