Companies House API jquery ajax returning 401












1















I'm trying to return json from gov.uk companies house API but I'm getting a 401




Failed to load resource: the server responded with a status of 401 (Unauthorized)




I'm using jQuery using the ajax() method and my code looks like this:



var chApiKey = "{{MYAPIKEY}}:";
var company_number = "09963675";

$.ajax({
async: false,
url: "https://api.companieshouse.gov.uk/company/",
type: "GET",
crossDomain: true,
contentType: "application/json",
data: company_number,
dataType: 'jsonp',
success: function(data) {
//Response text
alert(data);
},
beforeSend: function(xhr) {
xhr.withCredentials = true;
xhr.setRequestHeader("Authorization", make_base_auth(encodeURIComponent(chApiKey)))
// xhr.setRequestHeader ("Authorization", make_base_auth(chApiKey))
},
error: function() {
//Gat failure
console.log("error");
}
});

function make_base_auth(user) {
// var user = user + ":"
console.log("the api is: " + user)
var hash = btoa(user);
return "Basic " + hash;
// console.log("Basic " + hash + ":");
}


The instructions on gov.uk allow you to test with you API key which works. I've also return the json using a curl command in the terminal



curl -u{{MYAPIKEY}}: https://api.companieshouse.gov.uk/company/09963675









share|improve this question

























  • Your code looks fine, aside from the use of async: false which needs to be removed. Check their documentation to ensure that you are encoding your API key correctly, and also that your API key is valid.

    – Rory McCrossan
    Nov 16 '18 at 11:41











  • $.ajax allows you to specify username and password as parameters, you don’t need to create the Authorization header yourself. So try with those instead (specify an empty string for the password), and see if you get a different result.

    – misorude
    Nov 16 '18 at 11:55








  • 1





    I think you get ? in your URL (like "api.companieshouse.gov.uk/company?09963675")

    – barbsan
    Nov 16 '18 at 11:57











  • The key appears to be valid, using their curl example I get a json response as expected. I can't see any detail about which method to encode the key. They simply say to use the basic html authentification without a password. Removing the async parameter had no impact on the auth error. Switching from jsonp to json fires the CORS error, so I've stuck with jsonp for the time being. I've also tried passing username and password as options rather than setting the header and still the auth error persists.

    – Ty Fairclough
    Nov 19 '18 at 16:51
















1















I'm trying to return json from gov.uk companies house API but I'm getting a 401




Failed to load resource: the server responded with a status of 401 (Unauthorized)




I'm using jQuery using the ajax() method and my code looks like this:



var chApiKey = "{{MYAPIKEY}}:";
var company_number = "09963675";

$.ajax({
async: false,
url: "https://api.companieshouse.gov.uk/company/",
type: "GET",
crossDomain: true,
contentType: "application/json",
data: company_number,
dataType: 'jsonp',
success: function(data) {
//Response text
alert(data);
},
beforeSend: function(xhr) {
xhr.withCredentials = true;
xhr.setRequestHeader("Authorization", make_base_auth(encodeURIComponent(chApiKey)))
// xhr.setRequestHeader ("Authorization", make_base_auth(chApiKey))
},
error: function() {
//Gat failure
console.log("error");
}
});

function make_base_auth(user) {
// var user = user + ":"
console.log("the api is: " + user)
var hash = btoa(user);
return "Basic " + hash;
// console.log("Basic " + hash + ":");
}


The instructions on gov.uk allow you to test with you API key which works. I've also return the json using a curl command in the terminal



curl -u{{MYAPIKEY}}: https://api.companieshouse.gov.uk/company/09963675









share|improve this question

























  • Your code looks fine, aside from the use of async: false which needs to be removed. Check their documentation to ensure that you are encoding your API key correctly, and also that your API key is valid.

    – Rory McCrossan
    Nov 16 '18 at 11:41











  • $.ajax allows you to specify username and password as parameters, you don’t need to create the Authorization header yourself. So try with those instead (specify an empty string for the password), and see if you get a different result.

    – misorude
    Nov 16 '18 at 11:55








  • 1





    I think you get ? in your URL (like "api.companieshouse.gov.uk/company?09963675")

    – barbsan
    Nov 16 '18 at 11:57











  • The key appears to be valid, using their curl example I get a json response as expected. I can't see any detail about which method to encode the key. They simply say to use the basic html authentification without a password. Removing the async parameter had no impact on the auth error. Switching from jsonp to json fires the CORS error, so I've stuck with jsonp for the time being. I've also tried passing username and password as options rather than setting the header and still the auth error persists.

    – Ty Fairclough
    Nov 19 '18 at 16:51














1












1








1








I'm trying to return json from gov.uk companies house API but I'm getting a 401




Failed to load resource: the server responded with a status of 401 (Unauthorized)




I'm using jQuery using the ajax() method and my code looks like this:



var chApiKey = "{{MYAPIKEY}}:";
var company_number = "09963675";

$.ajax({
async: false,
url: "https://api.companieshouse.gov.uk/company/",
type: "GET",
crossDomain: true,
contentType: "application/json",
data: company_number,
dataType: 'jsonp',
success: function(data) {
//Response text
alert(data);
},
beforeSend: function(xhr) {
xhr.withCredentials = true;
xhr.setRequestHeader("Authorization", make_base_auth(encodeURIComponent(chApiKey)))
// xhr.setRequestHeader ("Authorization", make_base_auth(chApiKey))
},
error: function() {
//Gat failure
console.log("error");
}
});

function make_base_auth(user) {
// var user = user + ":"
console.log("the api is: " + user)
var hash = btoa(user);
return "Basic " + hash;
// console.log("Basic " + hash + ":");
}


The instructions on gov.uk allow you to test with you API key which works. I've also return the json using a curl command in the terminal



curl -u{{MYAPIKEY}}: https://api.companieshouse.gov.uk/company/09963675









share|improve this question
















I'm trying to return json from gov.uk companies house API but I'm getting a 401




Failed to load resource: the server responded with a status of 401 (Unauthorized)




I'm using jQuery using the ajax() method and my code looks like this:



var chApiKey = "{{MYAPIKEY}}:";
var company_number = "09963675";

$.ajax({
async: false,
url: "https://api.companieshouse.gov.uk/company/",
type: "GET",
crossDomain: true,
contentType: "application/json",
data: company_number,
dataType: 'jsonp',
success: function(data) {
//Response text
alert(data);
},
beforeSend: function(xhr) {
xhr.withCredentials = true;
xhr.setRequestHeader("Authorization", make_base_auth(encodeURIComponent(chApiKey)))
// xhr.setRequestHeader ("Authorization", make_base_auth(chApiKey))
},
error: function() {
//Gat failure
console.log("error");
}
});

function make_base_auth(user) {
// var user = user + ":"
console.log("the api is: " + user)
var hash = btoa(user);
return "Basic " + hash;
// console.log("Basic " + hash + ":");
}


The instructions on gov.uk allow you to test with you API key which works. I've also return the json using a curl command in the terminal



curl -u{{MYAPIKEY}}: https://api.companieshouse.gov.uk/company/09963675






javascript jquery ajax






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 16 '18 at 11:42









Rory McCrossan

250k29217254




250k29217254










asked Nov 16 '18 at 11:33









Ty FaircloughTy Fairclough

62




62













  • Your code looks fine, aside from the use of async: false which needs to be removed. Check their documentation to ensure that you are encoding your API key correctly, and also that your API key is valid.

    – Rory McCrossan
    Nov 16 '18 at 11:41











  • $.ajax allows you to specify username and password as parameters, you don’t need to create the Authorization header yourself. So try with those instead (specify an empty string for the password), and see if you get a different result.

    – misorude
    Nov 16 '18 at 11:55








  • 1





    I think you get ? in your URL (like "api.companieshouse.gov.uk/company?09963675")

    – barbsan
    Nov 16 '18 at 11:57











  • The key appears to be valid, using their curl example I get a json response as expected. I can't see any detail about which method to encode the key. They simply say to use the basic html authentification without a password. Removing the async parameter had no impact on the auth error. Switching from jsonp to json fires the CORS error, so I've stuck with jsonp for the time being. I've also tried passing username and password as options rather than setting the header and still the auth error persists.

    – Ty Fairclough
    Nov 19 '18 at 16:51



















  • Your code looks fine, aside from the use of async: false which needs to be removed. Check their documentation to ensure that you are encoding your API key correctly, and also that your API key is valid.

    – Rory McCrossan
    Nov 16 '18 at 11:41











  • $.ajax allows you to specify username and password as parameters, you don’t need to create the Authorization header yourself. So try with those instead (specify an empty string for the password), and see if you get a different result.

    – misorude
    Nov 16 '18 at 11:55








  • 1





    I think you get ? in your URL (like "api.companieshouse.gov.uk/company?09963675")

    – barbsan
    Nov 16 '18 at 11:57











  • The key appears to be valid, using their curl example I get a json response as expected. I can't see any detail about which method to encode the key. They simply say to use the basic html authentification without a password. Removing the async parameter had no impact on the auth error. Switching from jsonp to json fires the CORS error, so I've stuck with jsonp for the time being. I've also tried passing username and password as options rather than setting the header and still the auth error persists.

    – Ty Fairclough
    Nov 19 '18 at 16:51

















Your code looks fine, aside from the use of async: false which needs to be removed. Check their documentation to ensure that you are encoding your API key correctly, and also that your API key is valid.

– Rory McCrossan
Nov 16 '18 at 11:41





Your code looks fine, aside from the use of async: false which needs to be removed. Check their documentation to ensure that you are encoding your API key correctly, and also that your API key is valid.

– Rory McCrossan
Nov 16 '18 at 11:41













$.ajax allows you to specify username and password as parameters, you don’t need to create the Authorization header yourself. So try with those instead (specify an empty string for the password), and see if you get a different result.

– misorude
Nov 16 '18 at 11:55







$.ajax allows you to specify username and password as parameters, you don’t need to create the Authorization header yourself. So try with those instead (specify an empty string for the password), and see if you get a different result.

– misorude
Nov 16 '18 at 11:55






1




1





I think you get ? in your URL (like "api.companieshouse.gov.uk/company?09963675")

– barbsan
Nov 16 '18 at 11:57





I think you get ? in your URL (like "api.companieshouse.gov.uk/company?09963675")

– barbsan
Nov 16 '18 at 11:57













The key appears to be valid, using their curl example I get a json response as expected. I can't see any detail about which method to encode the key. They simply say to use the basic html authentification without a password. Removing the async parameter had no impact on the auth error. Switching from jsonp to json fires the CORS error, so I've stuck with jsonp for the time being. I've also tried passing username and password as options rather than setting the header and still the auth error persists.

– Ty Fairclough
Nov 19 '18 at 16:51





The key appears to be valid, using their curl example I get a json response as expected. I can't see any detail about which method to encode the key. They simply say to use the basic html authentification without a password. Removing the async parameter had no impact on the auth error. Switching from jsonp to json fires the CORS error, so I've stuck with jsonp for the time being. I've also tried passing username and password as options rather than setting the header and still the auth error persists.

– Ty Fairclough
Nov 19 '18 at 16:51












2 Answers
2






active

oldest

votes


















0














Propably your get different URL than you expect (with ?, because that's how data in appended in GET request to URL).



You need to add company_number to URL (and propably remove dataType: 'jsonp'):



url: "https://api.companieshouse.gov.uk/company/" + company_number,


Snippet below shows URL for your request in 3 cases:




  1. your current code

  2. your code after dataType: 'jsonp' removal


  3. company_number added directly to url





var chApiKey = "{{MYAPIKEY}}:";
var company_number = "09963675";

$.ajax({
async: false,
url: "https://api.companieshouse.gov.uk/company/",
type: "GET",
crossDomain: true,
contentType: "application/json",
data: company_number,
dataType: 'jsonp',
success: function(data) {
//Response text
alert(data);
},
beforeSend: function(xhr, settings) {
console.log("dataType: 'jsonp' :", settings.url)
xhr.withCredentials = true;
xhr.setRequestHeader("Authorization", make_base_auth(encodeURIComponent(chApiKey)))
// xhr.setRequestHeader ("Authorization", make_base_auth(chApiKey))
},
error: function() {
//Gat failure
//console.log("error");
}
});

function make_base_auth(user) {
// var user = user + ":"
//console.log("the api is: " + user)
var hash = btoa(user);
return "Basic " + hash;
// console.log("Basic " + hash + ":");
}

$.ajax({
async: false,
url: "https://api.companieshouse.gov.uk/company/",
type: "GET",
crossDomain: true,
contentType: "application/json",
data: company_number,
success: function(data) {
//Response text
alert(data);
},
beforeSend: function(xhr, settings) {
console.log("dataType: 'jsonp' removed :", settings.url)
xhr.withCredentials = true;
xhr.setRequestHeader("Authorization", make_base_auth(encodeURIComponent(chApiKey)))
// xhr.setRequestHeader ("Authorization", make_base_auth(chApiKey))
},
error: function() {
//Gat failure
//console.log("error");
}
});

$.ajax({
async: false,
url: "https://api.companieshouse.gov.uk/company/" + company_number,
type: "GET",
crossDomain: true,
contentType: "application/json",
success: function(data) {
//Response text
alert(data);
},
beforeSend: function(xhr, settings) {
console.log("company number added in url :", settings.url)
xhr.withCredentials = true;
xhr.setRequestHeader("Authorization", make_base_auth(encodeURIComponent(chApiKey)))
// xhr.setRequestHeader ("Authorization", make_base_auth(chApiKey))
},
error: function() {
//Gat failure
//console.log("error");
}
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>








share|improve this answer


























  • The api returns results without appending a query ? Here's their curl example showing this 'curl -uYOUR_APIKEY_FOLLOWED_BY_A_COLON: api.companieshouse.gov.uk/company{company_number}' Reference page: link

    – Ty Fairclough
    Nov 19 '18 at 16:22











  • That example has no query parameters, although they called it so. Query parameters are added after ? (like yoururl.com/subpage?paramname=paramvalue), but there's no ? in that example. Your company_number should be added to url, because in your example there's / between url and this "query parameter". Have you clicked Run code snippet? This will show you url you've requested (BTW. propably you should pass "Authorization" header as "Basic " + btoa(user + ":") I didn't focus on it in my answer)

    – barbsan
    Nov 20 '18 at 7:02



















0














In the https://developer.companieshouse.gov.uk app settings a field labeled: JavaScript domains must:




  • include the port number if used

  • Can not be localhost


For a local install update the hosts file and update the JavaScripts domains in the app settings.



I had made the mistake of not including the :3000 in this field. so my local domain was http://ch-test.com but should of been http://ch-test.com:3000 as my http server was running on port 3000.



Further to others feedback also changed



dataType: 'jsonp',
=>
dataType: 'json',



async: true,
=>
async: false,






share|improve this answer
























    Your Answer






    StackExchange.ifUsing("editor", function () {
    StackExchange.using("externalEditor", function () {
    StackExchange.using("snippets", function () {
    StackExchange.snippets.init();
    });
    });
    }, "code-snippets");

    StackExchange.ready(function() {
    var channelOptions = {
    tags: "".split(" "),
    id: "1"
    };
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function() {
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled) {
    StackExchange.using("snippets", function() {
    createEditor();
    });
    }
    else {
    createEditor();
    }
    });

    function createEditor() {
    StackExchange.prepareEditor({
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader: {
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    },
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    });


    }
    });














    draft saved

    draft discarded


















    StackExchange.ready(
    function () {
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53337039%2fcompanies-house-api-jquery-ajax-returning-401%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    2 Answers
    2






    active

    oldest

    votes








    2 Answers
    2






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    0














    Propably your get different URL than you expect (with ?, because that's how data in appended in GET request to URL).



    You need to add company_number to URL (and propably remove dataType: 'jsonp'):



    url: "https://api.companieshouse.gov.uk/company/" + company_number,


    Snippet below shows URL for your request in 3 cases:




    1. your current code

    2. your code after dataType: 'jsonp' removal


    3. company_number added directly to url





    var chApiKey = "{{MYAPIKEY}}:";
    var company_number = "09963675";

    $.ajax({
    async: false,
    url: "https://api.companieshouse.gov.uk/company/",
    type: "GET",
    crossDomain: true,
    contentType: "application/json",
    data: company_number,
    dataType: 'jsonp',
    success: function(data) {
    //Response text
    alert(data);
    },
    beforeSend: function(xhr, settings) {
    console.log("dataType: 'jsonp' :", settings.url)
    xhr.withCredentials = true;
    xhr.setRequestHeader("Authorization", make_base_auth(encodeURIComponent(chApiKey)))
    // xhr.setRequestHeader ("Authorization", make_base_auth(chApiKey))
    },
    error: function() {
    //Gat failure
    //console.log("error");
    }
    });

    function make_base_auth(user) {
    // var user = user + ":"
    //console.log("the api is: " + user)
    var hash = btoa(user);
    return "Basic " + hash;
    // console.log("Basic " + hash + ":");
    }

    $.ajax({
    async: false,
    url: "https://api.companieshouse.gov.uk/company/",
    type: "GET",
    crossDomain: true,
    contentType: "application/json",
    data: company_number,
    success: function(data) {
    //Response text
    alert(data);
    },
    beforeSend: function(xhr, settings) {
    console.log("dataType: 'jsonp' removed :", settings.url)
    xhr.withCredentials = true;
    xhr.setRequestHeader("Authorization", make_base_auth(encodeURIComponent(chApiKey)))
    // xhr.setRequestHeader ("Authorization", make_base_auth(chApiKey))
    },
    error: function() {
    //Gat failure
    //console.log("error");
    }
    });

    $.ajax({
    async: false,
    url: "https://api.companieshouse.gov.uk/company/" + company_number,
    type: "GET",
    crossDomain: true,
    contentType: "application/json",
    success: function(data) {
    //Response text
    alert(data);
    },
    beforeSend: function(xhr, settings) {
    console.log("company number added in url :", settings.url)
    xhr.withCredentials = true;
    xhr.setRequestHeader("Authorization", make_base_auth(encodeURIComponent(chApiKey)))
    // xhr.setRequestHeader ("Authorization", make_base_auth(chApiKey))
    },
    error: function() {
    //Gat failure
    //console.log("error");
    }
    });

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>








    share|improve this answer


























    • The api returns results without appending a query ? Here's their curl example showing this 'curl -uYOUR_APIKEY_FOLLOWED_BY_A_COLON: api.companieshouse.gov.uk/company{company_number}' Reference page: link

      – Ty Fairclough
      Nov 19 '18 at 16:22











    • That example has no query parameters, although they called it so. Query parameters are added after ? (like yoururl.com/subpage?paramname=paramvalue), but there's no ? in that example. Your company_number should be added to url, because in your example there's / between url and this "query parameter". Have you clicked Run code snippet? This will show you url you've requested (BTW. propably you should pass "Authorization" header as "Basic " + btoa(user + ":") I didn't focus on it in my answer)

      – barbsan
      Nov 20 '18 at 7:02
















    0














    Propably your get different URL than you expect (with ?, because that's how data in appended in GET request to URL).



    You need to add company_number to URL (and propably remove dataType: 'jsonp'):



    url: "https://api.companieshouse.gov.uk/company/" + company_number,


    Snippet below shows URL for your request in 3 cases:




    1. your current code

    2. your code after dataType: 'jsonp' removal


    3. company_number added directly to url





    var chApiKey = "{{MYAPIKEY}}:";
    var company_number = "09963675";

    $.ajax({
    async: false,
    url: "https://api.companieshouse.gov.uk/company/",
    type: "GET",
    crossDomain: true,
    contentType: "application/json",
    data: company_number,
    dataType: 'jsonp',
    success: function(data) {
    //Response text
    alert(data);
    },
    beforeSend: function(xhr, settings) {
    console.log("dataType: 'jsonp' :", settings.url)
    xhr.withCredentials = true;
    xhr.setRequestHeader("Authorization", make_base_auth(encodeURIComponent(chApiKey)))
    // xhr.setRequestHeader ("Authorization", make_base_auth(chApiKey))
    },
    error: function() {
    //Gat failure
    //console.log("error");
    }
    });

    function make_base_auth(user) {
    // var user = user + ":"
    //console.log("the api is: " + user)
    var hash = btoa(user);
    return "Basic " + hash;
    // console.log("Basic " + hash + ":");
    }

    $.ajax({
    async: false,
    url: "https://api.companieshouse.gov.uk/company/",
    type: "GET",
    crossDomain: true,
    contentType: "application/json",
    data: company_number,
    success: function(data) {
    //Response text
    alert(data);
    },
    beforeSend: function(xhr, settings) {
    console.log("dataType: 'jsonp' removed :", settings.url)
    xhr.withCredentials = true;
    xhr.setRequestHeader("Authorization", make_base_auth(encodeURIComponent(chApiKey)))
    // xhr.setRequestHeader ("Authorization", make_base_auth(chApiKey))
    },
    error: function() {
    //Gat failure
    //console.log("error");
    }
    });

    $.ajax({
    async: false,
    url: "https://api.companieshouse.gov.uk/company/" + company_number,
    type: "GET",
    crossDomain: true,
    contentType: "application/json",
    success: function(data) {
    //Response text
    alert(data);
    },
    beforeSend: function(xhr, settings) {
    console.log("company number added in url :", settings.url)
    xhr.withCredentials = true;
    xhr.setRequestHeader("Authorization", make_base_auth(encodeURIComponent(chApiKey)))
    // xhr.setRequestHeader ("Authorization", make_base_auth(chApiKey))
    },
    error: function() {
    //Gat failure
    //console.log("error");
    }
    });

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>








    share|improve this answer


























    • The api returns results without appending a query ? Here's their curl example showing this 'curl -uYOUR_APIKEY_FOLLOWED_BY_A_COLON: api.companieshouse.gov.uk/company{company_number}' Reference page: link

      – Ty Fairclough
      Nov 19 '18 at 16:22











    • That example has no query parameters, although they called it so. Query parameters are added after ? (like yoururl.com/subpage?paramname=paramvalue), but there's no ? in that example. Your company_number should be added to url, because in your example there's / between url and this "query parameter". Have you clicked Run code snippet? This will show you url you've requested (BTW. propably you should pass "Authorization" header as "Basic " + btoa(user + ":") I didn't focus on it in my answer)

      – barbsan
      Nov 20 '18 at 7:02














    0












    0








    0







    Propably your get different URL than you expect (with ?, because that's how data in appended in GET request to URL).



    You need to add company_number to URL (and propably remove dataType: 'jsonp'):



    url: "https://api.companieshouse.gov.uk/company/" + company_number,


    Snippet below shows URL for your request in 3 cases:




    1. your current code

    2. your code after dataType: 'jsonp' removal


    3. company_number added directly to url





    var chApiKey = "{{MYAPIKEY}}:";
    var company_number = "09963675";

    $.ajax({
    async: false,
    url: "https://api.companieshouse.gov.uk/company/",
    type: "GET",
    crossDomain: true,
    contentType: "application/json",
    data: company_number,
    dataType: 'jsonp',
    success: function(data) {
    //Response text
    alert(data);
    },
    beforeSend: function(xhr, settings) {
    console.log("dataType: 'jsonp' :", settings.url)
    xhr.withCredentials = true;
    xhr.setRequestHeader("Authorization", make_base_auth(encodeURIComponent(chApiKey)))
    // xhr.setRequestHeader ("Authorization", make_base_auth(chApiKey))
    },
    error: function() {
    //Gat failure
    //console.log("error");
    }
    });

    function make_base_auth(user) {
    // var user = user + ":"
    //console.log("the api is: " + user)
    var hash = btoa(user);
    return "Basic " + hash;
    // console.log("Basic " + hash + ":");
    }

    $.ajax({
    async: false,
    url: "https://api.companieshouse.gov.uk/company/",
    type: "GET",
    crossDomain: true,
    contentType: "application/json",
    data: company_number,
    success: function(data) {
    //Response text
    alert(data);
    },
    beforeSend: function(xhr, settings) {
    console.log("dataType: 'jsonp' removed :", settings.url)
    xhr.withCredentials = true;
    xhr.setRequestHeader("Authorization", make_base_auth(encodeURIComponent(chApiKey)))
    // xhr.setRequestHeader ("Authorization", make_base_auth(chApiKey))
    },
    error: function() {
    //Gat failure
    //console.log("error");
    }
    });

    $.ajax({
    async: false,
    url: "https://api.companieshouse.gov.uk/company/" + company_number,
    type: "GET",
    crossDomain: true,
    contentType: "application/json",
    success: function(data) {
    //Response text
    alert(data);
    },
    beforeSend: function(xhr, settings) {
    console.log("company number added in url :", settings.url)
    xhr.withCredentials = true;
    xhr.setRequestHeader("Authorization", make_base_auth(encodeURIComponent(chApiKey)))
    // xhr.setRequestHeader ("Authorization", make_base_auth(chApiKey))
    },
    error: function() {
    //Gat failure
    //console.log("error");
    }
    });

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>








    share|improve this answer















    Propably your get different URL than you expect (with ?, because that's how data in appended in GET request to URL).



    You need to add company_number to URL (and propably remove dataType: 'jsonp'):



    url: "https://api.companieshouse.gov.uk/company/" + company_number,


    Snippet below shows URL for your request in 3 cases:




    1. your current code

    2. your code after dataType: 'jsonp' removal


    3. company_number added directly to url





    var chApiKey = "{{MYAPIKEY}}:";
    var company_number = "09963675";

    $.ajax({
    async: false,
    url: "https://api.companieshouse.gov.uk/company/",
    type: "GET",
    crossDomain: true,
    contentType: "application/json",
    data: company_number,
    dataType: 'jsonp',
    success: function(data) {
    //Response text
    alert(data);
    },
    beforeSend: function(xhr, settings) {
    console.log("dataType: 'jsonp' :", settings.url)
    xhr.withCredentials = true;
    xhr.setRequestHeader("Authorization", make_base_auth(encodeURIComponent(chApiKey)))
    // xhr.setRequestHeader ("Authorization", make_base_auth(chApiKey))
    },
    error: function() {
    //Gat failure
    //console.log("error");
    }
    });

    function make_base_auth(user) {
    // var user = user + ":"
    //console.log("the api is: " + user)
    var hash = btoa(user);
    return "Basic " + hash;
    // console.log("Basic " + hash + ":");
    }

    $.ajax({
    async: false,
    url: "https://api.companieshouse.gov.uk/company/",
    type: "GET",
    crossDomain: true,
    contentType: "application/json",
    data: company_number,
    success: function(data) {
    //Response text
    alert(data);
    },
    beforeSend: function(xhr, settings) {
    console.log("dataType: 'jsonp' removed :", settings.url)
    xhr.withCredentials = true;
    xhr.setRequestHeader("Authorization", make_base_auth(encodeURIComponent(chApiKey)))
    // xhr.setRequestHeader ("Authorization", make_base_auth(chApiKey))
    },
    error: function() {
    //Gat failure
    //console.log("error");
    }
    });

    $.ajax({
    async: false,
    url: "https://api.companieshouse.gov.uk/company/" + company_number,
    type: "GET",
    crossDomain: true,
    contentType: "application/json",
    success: function(data) {
    //Response text
    alert(data);
    },
    beforeSend: function(xhr, settings) {
    console.log("company number added in url :", settings.url)
    xhr.withCredentials = true;
    xhr.setRequestHeader("Authorization", make_base_auth(encodeURIComponent(chApiKey)))
    // xhr.setRequestHeader ("Authorization", make_base_auth(chApiKey))
    },
    error: function() {
    //Gat failure
    //console.log("error");
    }
    });

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>








    var chApiKey = "{{MYAPIKEY}}:";
    var company_number = "09963675";

    $.ajax({
    async: false,
    url: "https://api.companieshouse.gov.uk/company/",
    type: "GET",
    crossDomain: true,
    contentType: "application/json",
    data: company_number,
    dataType: 'jsonp',
    success: function(data) {
    //Response text
    alert(data);
    },
    beforeSend: function(xhr, settings) {
    console.log("dataType: 'jsonp' :", settings.url)
    xhr.withCredentials = true;
    xhr.setRequestHeader("Authorization", make_base_auth(encodeURIComponent(chApiKey)))
    // xhr.setRequestHeader ("Authorization", make_base_auth(chApiKey))
    },
    error: function() {
    //Gat failure
    //console.log("error");
    }
    });

    function make_base_auth(user) {
    // var user = user + ":"
    //console.log("the api is: " + user)
    var hash = btoa(user);
    return "Basic " + hash;
    // console.log("Basic " + hash + ":");
    }

    $.ajax({
    async: false,
    url: "https://api.companieshouse.gov.uk/company/",
    type: "GET",
    crossDomain: true,
    contentType: "application/json",
    data: company_number,
    success: function(data) {
    //Response text
    alert(data);
    },
    beforeSend: function(xhr, settings) {
    console.log("dataType: 'jsonp' removed :", settings.url)
    xhr.withCredentials = true;
    xhr.setRequestHeader("Authorization", make_base_auth(encodeURIComponent(chApiKey)))
    // xhr.setRequestHeader ("Authorization", make_base_auth(chApiKey))
    },
    error: function() {
    //Gat failure
    //console.log("error");
    }
    });

    $.ajax({
    async: false,
    url: "https://api.companieshouse.gov.uk/company/" + company_number,
    type: "GET",
    crossDomain: true,
    contentType: "application/json",
    success: function(data) {
    //Response text
    alert(data);
    },
    beforeSend: function(xhr, settings) {
    console.log("company number added in url :", settings.url)
    xhr.withCredentials = true;
    xhr.setRequestHeader("Authorization", make_base_auth(encodeURIComponent(chApiKey)))
    // xhr.setRequestHeader ("Authorization", make_base_auth(chApiKey))
    },
    error: function() {
    //Gat failure
    //console.log("error");
    }
    });

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>





    var chApiKey = "{{MYAPIKEY}}:";
    var company_number = "09963675";

    $.ajax({
    async: false,
    url: "https://api.companieshouse.gov.uk/company/",
    type: "GET",
    crossDomain: true,
    contentType: "application/json",
    data: company_number,
    dataType: 'jsonp',
    success: function(data) {
    //Response text
    alert(data);
    },
    beforeSend: function(xhr, settings) {
    console.log("dataType: 'jsonp' :", settings.url)
    xhr.withCredentials = true;
    xhr.setRequestHeader("Authorization", make_base_auth(encodeURIComponent(chApiKey)))
    // xhr.setRequestHeader ("Authorization", make_base_auth(chApiKey))
    },
    error: function() {
    //Gat failure
    //console.log("error");
    }
    });

    function make_base_auth(user) {
    // var user = user + ":"
    //console.log("the api is: " + user)
    var hash = btoa(user);
    return "Basic " + hash;
    // console.log("Basic " + hash + ":");
    }

    $.ajax({
    async: false,
    url: "https://api.companieshouse.gov.uk/company/",
    type: "GET",
    crossDomain: true,
    contentType: "application/json",
    data: company_number,
    success: function(data) {
    //Response text
    alert(data);
    },
    beforeSend: function(xhr, settings) {
    console.log("dataType: 'jsonp' removed :", settings.url)
    xhr.withCredentials = true;
    xhr.setRequestHeader("Authorization", make_base_auth(encodeURIComponent(chApiKey)))
    // xhr.setRequestHeader ("Authorization", make_base_auth(chApiKey))
    },
    error: function() {
    //Gat failure
    //console.log("error");
    }
    });

    $.ajax({
    async: false,
    url: "https://api.companieshouse.gov.uk/company/" + company_number,
    type: "GET",
    crossDomain: true,
    contentType: "application/json",
    success: function(data) {
    //Response text
    alert(data);
    },
    beforeSend: function(xhr, settings) {
    console.log("company number added in url :", settings.url)
    xhr.withCredentials = true;
    xhr.setRequestHeader("Authorization", make_base_auth(encodeURIComponent(chApiKey)))
    // xhr.setRequestHeader ("Authorization", make_base_auth(chApiKey))
    },
    error: function() {
    //Gat failure
    //console.log("error");
    }
    });

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>






    share|improve this answer














    share|improve this answer



    share|improve this answer








    edited Nov 16 '18 at 12:20

























    answered Nov 16 '18 at 12:11









    barbsanbarbsan

    2,62961524




    2,62961524













    • The api returns results without appending a query ? Here's their curl example showing this 'curl -uYOUR_APIKEY_FOLLOWED_BY_A_COLON: api.companieshouse.gov.uk/company{company_number}' Reference page: link

      – Ty Fairclough
      Nov 19 '18 at 16:22











    • That example has no query parameters, although they called it so. Query parameters are added after ? (like yoururl.com/subpage?paramname=paramvalue), but there's no ? in that example. Your company_number should be added to url, because in your example there's / between url and this "query parameter". Have you clicked Run code snippet? This will show you url you've requested (BTW. propably you should pass "Authorization" header as "Basic " + btoa(user + ":") I didn't focus on it in my answer)

      – barbsan
      Nov 20 '18 at 7:02



















    • The api returns results without appending a query ? Here's their curl example showing this 'curl -uYOUR_APIKEY_FOLLOWED_BY_A_COLON: api.companieshouse.gov.uk/company{company_number}' Reference page: link

      – Ty Fairclough
      Nov 19 '18 at 16:22











    • That example has no query parameters, although they called it so. Query parameters are added after ? (like yoururl.com/subpage?paramname=paramvalue), but there's no ? in that example. Your company_number should be added to url, because in your example there's / between url and this "query parameter". Have you clicked Run code snippet? This will show you url you've requested (BTW. propably you should pass "Authorization" header as "Basic " + btoa(user + ":") I didn't focus on it in my answer)

      – barbsan
      Nov 20 '18 at 7:02

















    The api returns results without appending a query ? Here's their curl example showing this 'curl -uYOUR_APIKEY_FOLLOWED_BY_A_COLON: api.companieshouse.gov.uk/company{company_number}' Reference page: link

    – Ty Fairclough
    Nov 19 '18 at 16:22





    The api returns results without appending a query ? Here's their curl example showing this 'curl -uYOUR_APIKEY_FOLLOWED_BY_A_COLON: api.companieshouse.gov.uk/company{company_number}' Reference page: link

    – Ty Fairclough
    Nov 19 '18 at 16:22













    That example has no query parameters, although they called it so. Query parameters are added after ? (like yoururl.com/subpage?paramname=paramvalue), but there's no ? in that example. Your company_number should be added to url, because in your example there's / between url and this "query parameter". Have you clicked Run code snippet? This will show you url you've requested (BTW. propably you should pass "Authorization" header as "Basic " + btoa(user + ":") I didn't focus on it in my answer)

    – barbsan
    Nov 20 '18 at 7:02





    That example has no query parameters, although they called it so. Query parameters are added after ? (like yoururl.com/subpage?paramname=paramvalue), but there's no ? in that example. Your company_number should be added to url, because in your example there's / between url and this "query parameter". Have you clicked Run code snippet? This will show you url you've requested (BTW. propably you should pass "Authorization" header as "Basic " + btoa(user + ":") I didn't focus on it in my answer)

    – barbsan
    Nov 20 '18 at 7:02













    0














    In the https://developer.companieshouse.gov.uk app settings a field labeled: JavaScript domains must:




    • include the port number if used

    • Can not be localhost


    For a local install update the hosts file and update the JavaScripts domains in the app settings.



    I had made the mistake of not including the :3000 in this field. so my local domain was http://ch-test.com but should of been http://ch-test.com:3000 as my http server was running on port 3000.



    Further to others feedback also changed



    dataType: 'jsonp',
    =>
    dataType: 'json',



    async: true,
    =>
    async: false,






    share|improve this answer




























      0














      In the https://developer.companieshouse.gov.uk app settings a field labeled: JavaScript domains must:




      • include the port number if used

      • Can not be localhost


      For a local install update the hosts file and update the JavaScripts domains in the app settings.



      I had made the mistake of not including the :3000 in this field. so my local domain was http://ch-test.com but should of been http://ch-test.com:3000 as my http server was running on port 3000.



      Further to others feedback also changed



      dataType: 'jsonp',
      =>
      dataType: 'json',



      async: true,
      =>
      async: false,






      share|improve this answer


























        0












        0








        0







        In the https://developer.companieshouse.gov.uk app settings a field labeled: JavaScript domains must:




        • include the port number if used

        • Can not be localhost


        For a local install update the hosts file and update the JavaScripts domains in the app settings.



        I had made the mistake of not including the :3000 in this field. so my local domain was http://ch-test.com but should of been http://ch-test.com:3000 as my http server was running on port 3000.



        Further to others feedback also changed



        dataType: 'jsonp',
        =>
        dataType: 'json',



        async: true,
        =>
        async: false,






        share|improve this answer













        In the https://developer.companieshouse.gov.uk app settings a field labeled: JavaScript domains must:




        • include the port number if used

        • Can not be localhost


        For a local install update the hosts file and update the JavaScripts domains in the app settings.



        I had made the mistake of not including the :3000 in this field. so my local domain was http://ch-test.com but should of been http://ch-test.com:3000 as my http server was running on port 3000.



        Further to others feedback also changed



        dataType: 'jsonp',
        =>
        dataType: 'json',



        async: true,
        =>
        async: false,







        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Nov 19 '18 at 17:28









        Ty FaircloughTy Fairclough

        62




        62






























            draft saved

            draft discarded




















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53337039%2fcompanies-house-api-jquery-ajax-returning-401%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            List item for chat from Array inside array React Native

            Thiostrepton

            Caerphilly