【发布时间】:2018-11-16 11:33:34
【问题描述】:
我正在尝试从 gov.uk 公司内部 API 返回 json,但我得到了 401
加载资源失败:服务器响应状态为 401(未授权)
我正在使用 ajax() 方法使用 jQuery,我的代码如下所示:
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 + ":");
}
gov.uk 上的说明允许您使用有效的 API 密钥进行测试。我还在终端中使用 curl 命令返回了 json
curl -u{{MYAPIKEY}}: https://api.companieshouse.gov.uk/company/09963675
【问题讨论】:
-
您的代码看起来不错,除了使用需要删除的
async: false。检查他们的文档以确保您正确编码 API 密钥,并且您的 API 密钥是有效的。 -
$.ajax 允许你指定
username和password作为参数,你不需要自己创建授权头。所以尝试使用那些(为密码指定一个空字符串),看看你是否得到不同的结果。 -
我认为您的网址中包含
?(例如“api.companieshouse.gov.uk/company?09963675"”) -
密钥似乎是有效的,使用他们的 curl 示例我得到了预期的 json 响应。我看不到有关对密钥进行编码的方法的任何详细信息。他们只是说使用没有密码的基本 html 身份验证。删除 async 参数对 auth 错误没有影响。从 jsonp 切换到 json 会触发 CORS 错误,所以我暂时坚持使用 jsonp。我还尝试将用户名和密码作为选项传递,而不是设置标题,但身份验证错误仍然存在。
标签: javascript jquery ajax