0

I'm trying to obtain data from my schools API with Ajax GET request with an API key, but I still get the 401 error message. I have included the API key in the header but it seems to not work.

Here's my code so far;

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;

Console message;

enter image description here

IlariM
  • 376
  • 1
  • 3
  • 16
  • Upload the code somewhere with the API key, it would be easier to help you. – hungersoft Mar 21 '18 at 15:05
  • 2
    Can you get the request to work in something like Postman? – Stretch0 Mar 21 '18 at 15:06
  • @Stretch0 I just tested Postman and yes, I actually got it using the Basic Auth. I inserted the API key in the username section and got the response body. I guess there's some easy way with jQuery to include the Basic Auth? – IlariM Mar 21 '18 at 15:17

1 Answers1

2

Sounds like you need to use basic auth.

You should be able to add your credentials to your request by doing something like 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;
}

Also, I would recommend using something like Axios for your http requests. You Don't really need JQuery with react and axios is based on fetch but handles errors better.

Stretch0
  • 8,362
  • 13
  • 71
  • 133