【问题标题】:React - ajax GET request with headers still returns 401 (Unauthorized)React - 带有标头的 ajax GET 请求仍返回 401(未经授权)
【发布时间】:2018-08-30 18:36:29
【问题描述】:

我正在尝试使用带有 API 密钥的 Ajax GET 请求从我的学校 API 获取数据,但我仍然收到 401 错误消息。我已在标头中包含 API 密钥,但它似乎不起作用。

这是我目前的代码;

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;

控制台消息;

【问题讨论】:

  • 使用API​​密钥上传代码,帮助你更容易。
  • 你能得到像 Postman 这样的工作的请求吗?
  • @Stretch0 我刚刚测试了 Postman,是的,我实际上是使用 Basic Auth 获得的。我在用户名部分插入了 API 密钥并获得了响应正文。我想 jQuery 有一些简单的方法可以包含基本身份验证?

标签: javascript ajax reactjs api httprequest


【解决方案1】:

听起来您需要使用基本身份验证。

您应该能够通过执行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 请求。你真的不需要 JQuery 和 react 和 axios 是基于 fetch 但更好地处理错误。

【讨论】:

  • 我一定会研究 Axios。谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-08-17
  • 2021-04-26
  • 1970-01-01
  • 2021-03-24
  • 2018-10-22
  • 1970-01-01
  • 2016-06-22
相关资源
最近更新 更多