因此,我正在创建对此 API 的 GET 请求:https://immense-depths-6983.herokuapp.com/search/ .
要在浏览器中测试的示例 URL 是:https://immense-depths-6983.herokuapp.com/search?search=94305
用户名是“admin”,密码是“password”。
在浏览器中运行示例 URL 会弹出一个窗口,要求进行身份验证,正确输入后,我会收到 JSON 响应文本。
但是,当我在代码上运行它时,它不起作用。我在网上搜索了答案,但每个解决方案都不起作用。我尝试过 admin:password@url,将用户名和密码作为 GET 请求中的数据参数传递,甚至使用 BTOA 哈希将其传递到 Web 服务器。可惜没有结果。我已经附上了我现在正在使用的代码 - 希望一些好心人可以帮助我解决这个问题。
---------代码--------------
render() {
var url = this.props.url;
var zip = '94305';
// var zip = this.props.zip;
// create the prop type later with built in functionality
var query = zip + this.props.query;
var username = "admin";
var password = "password";
var ret_data = textbookApi(url, query, username, password);
console.log("after");
// if data is null, ignore
// else
// this.setState({textbooks: ret_data});
return (
<div>
</div>
);
}
}
export default Search;
function makeBaseAuth(user, pswd) {
var token = user + ':' + pswd;
var hash = "";
if (btoa) {
hash = btoa(token);
}
return "Basic " + hash;
}
function textbookApi(url_link, query, username, password) {
// console.log("INSIDE");
console.log(makeBaseAuth(username, password));
$.ajax({
type: "GET",
url: url_link,
data: {
'search' : query
},
beforeSend: function (xhr) {
xhr.setRequestHeader('Authorization', makeBaseAuth(username, password));
},
success: function(data) {
console.log("WORKS!!!!!!!!!!!!!!!!!!!!!!!!!");
console.log(data);
return data;
}.bind(this),
error: function(xhr, status, err) {
console.error(url_link, status, err.toString());
}.bind(this)
});
}
最佳答案
尝试使用用户名和密码作为基本身份验证方法发送您的http header
我在 Jquery ajax 调用上尝试了这个方法
var settings = {
"async": true,
"crossDomain": true,
"url": "https://immense-depths-6983.herokuapp.com/search?search=94305",
"method": "GET",
"headers": {
"authorization": "Basic YWRtaW46cGFzc3dvcmQ=",
"cache-control": "no-cache",
"postman-token": "54733c33-4918-811b-3987-69d6edeaa3a0"
}
}
$.ajax(settings).done(function (response) {
console.log(response);
});
- 确保您从服务器端启用了跨域访问......并且没有收到任何与此相关的错误。
在 ajax http 中传递用户名和密码作为基本身份验证 方法。
它对我有用输出:
-[ -{ "id" : 0, "title" : Basic Electronics: An Introduction to Electronics for Science Students, "author" : Curtis Meyer, "no" : 0, "class" : , "isbn" : 5800066848142 }, -{ "id" : 0, "title" : Programming Abstractions in C++, "author" : Jerry Cain, "no" : 0, "class" : CS 106B CS 106X, "isbn" : 1 }, -{ "id" : 0, "title" : The Mind's Machine: Foundations of Brain and Behavior, "author" : Neil Verne Watson, "no" : 0, "class" : Think, "isbn" : 9780878939336 }, -{ "id" : 0, "title" : Physics for Scientists and Engineers: A Strategic Approach, "author" : Randall D. Knight, "no" : 0, "class" : Physics 41, "isbn" : 9780321752918 },.... .... ...
尝试 https://www.base64decode.org编码和解码
关于javascript - AJAX Jquery 调用返回 401(未经授权)- API 调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41011207/