我尝试使用带有 API key 的 Ajax GET 请求从我的学校 API 获取数据,但仍然收到 401 错误消息。我已将 API key 包含在 header 中,但它似乎不起作用。
这是到目前为止我的代码;
class App extends Component {
constructor(){
super();
this.state = {
todos:[]
}
}
getTodos(){
$.ajax({
type: "GET",
url: 'https://opendata.seamk.fi/r1/reservation/building/2',
dataType:'json',
headers: {
Authorization: "API_KEY"
},
cache: false,
success: function(data){
this.setState({todos: data}, function(){
console.log(this.state);
});
}.bind(this),
error: function(xhr, status, err){
console.log(err);
}
});
}
componentWillMount(){
this.getTodos();
}
componentDidMount(){
this.getTodos();
}
render() {
return (
<Titles />
<Todos todos={this.state.todos}/>
);
}
}
export default App;
控制台消息;
最佳答案
听起来您需要使用基本身份验证。
您应该能够通过执行类似 this 的操作将您的凭据添加到您的请求中:
$.ajax({
type: 'GET',
url: 'url',
dataType: 'json',
//whatever you need
beforeSend: function (xhr) {
xhr.setRequestHeader('Authorization', make_base_auth(user, password));
},
success: function () {});
});
function make_base_auth(user, password) {
var tok = user + ':' + password;
var hash = btoa(tok);
return 'Basic ' + hash;
}
此外,我建议使用类似 Axios 的内容。用于您的 http 请求。您实际上并不需要带有 React 的 JQuery,axios 基于 fetch,但可以更好地处理错误。
关于javascript - React - 带 header 的 ajax GET 请求仍然返回 401(未经授权),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49409761/