Companies House API jquery ajax returning 401
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
add a comment |
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
Your code looks fine, aside from the use ofasync: falsewhich 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 specifyusernameandpasswordas 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
add a comment |
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
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
javascript jquery ajax
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 ofasync: falsewhich 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 specifyusernameandpasswordas 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
add a comment |
Your code looks fine, aside from the use ofasync: falsewhich 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 specifyusernameandpasswordas 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
add a comment |
2 Answers
2
active
oldest
votes
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:
- your current code
- your code after
dataType: 'jsonp'removal
company_numberadded 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>
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?(likeyoururl.com/subpage?paramname=paramvalue), but there's no?in that example. Yourcompany_numbershould be added to url, because in your example there's/between url and this "query parameter". Have you clickedRun 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
add a comment |
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,
add a comment |
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
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
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
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:
- your current code
- your code after
dataType: 'jsonp'removal
company_numberadded 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>
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?(likeyoururl.com/subpage?paramname=paramvalue), but there's no?in that example. Yourcompany_numbershould be added to url, because in your example there's/between url and this "query parameter". Have you clickedRun 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
add a comment |
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:
- your current code
- your code after
dataType: 'jsonp'removal
company_numberadded 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>
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?(likeyoururl.com/subpage?paramname=paramvalue), but there's no?in that example. Yourcompany_numbershould be added to url, because in your example there's/between url and this "query parameter". Have you clickedRun 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
add a comment |
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:
- your current code
- your code after
dataType: 'jsonp'removal
company_numberadded 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>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:
- your current code
- your code after
dataType: 'jsonp'removal
company_numberadded 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>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?(likeyoururl.com/subpage?paramname=paramvalue), but there's no?in that example. Yourcompany_numbershould be added to url, because in your example there's/between url and this "query parameter". Have you clickedRun 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
add a comment |
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?(likeyoururl.com/subpage?paramname=paramvalue), but there's no?in that example. Yourcompany_numbershould be added to url, because in your example there's/between url and this "query parameter". Have you clickedRun 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
add a comment |
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,
add a comment |
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,
add a comment |
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,
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,
answered Nov 19 '18 at 17:28
Ty FaircloughTy Fairclough
62
62
add a comment |
add a comment |
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.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
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
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
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
Your code looks fine, aside from the use of
async: falsewhich 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
usernameandpasswordas 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