Skip to content

JavaScript pCloud API call to fetch userinfo gives an error

While calling the api from JavaScript

This HTTP request works fine https://api.pcloud.com/userinfo?username=xxxx@gmail.com&password=xxxx

In the below code I want to call via JavaScript

var user='email loggin';
var password='password of pcloud';

function make_base_auth(user, password) {
  var tok = user + ':' + password;
  var hash = btoa(tok);
  return "Basic " + hash;
}

$.ajax
  ({
    type: "GET",
    url: "https://api.pcloud.com/userinfo",
    dataType: 'json',
    async: false,
    data: '{}',
    beforeSend: function (xhr){ 
        xhr.setRequestHeader('Authorization', make_base_auth(username, password)); 
    },
    success: function (){
        alert('Working Fine'); 
    }
});

output in console

XMLHttpRequest cannot load https://api.pcloud.com/userinfo?{}. Request header field Authorization is not allowed by Access-Control-Allow-Headers in preflight response.

If someone can provide a solution or enhance the code.

Answer

Pass the username and password in the data field and remove the “beforeSend” part. For more information and examples, you can check out the pCloud Javascript SDK: https://github.com/pCloud/pcloud-sdk-js

Here is working example (a bit shorter):

$.getJSON("https://api.pcloud.com/userinfo", {
  username: "***", 
  password: "***"
}, function() {
  alert("working fine"); 
});