Search code examples
ruby-on-railsreactjsoauthruby-on-rails-5

How to add a BearerToken to React API Requests?


I am a beginner to React. I'm using React to make API requests like so:

class CatsApi {
  static createCat(cat) {
    const request = new Request('http://localhost:4300/api/v1/cats', {
      method: 'POST',
      headers: new Headers({
        'Content-Type': 'application/json'
      }),
      body: JSON.stringify(cat)
    });

    return fetch(request).then(response => {
      return response.json();
    }).catch(error => {
      return error;
    });
  }

Meanwhile, I have authentication to my API via react-devise: https://github.com/timscott/react-devise Which has a method getBearerToken like so: https://github.com/timscott/react-devise/blob/master/src/actions/authTokenStore.js

How do I use getBearerToken to pass the API the token so API requests are authenticated with the token?


Solution

  • You can use the Authorization header like:

    { 'Authorization': `Bearer ${authToken}` }
    

    Using fetch you could try with something like:

    fetch('http://localhost:4300/api/v1/cats', {
        method: 'POST',
        headers: {
            'Authorization': `Bearer ${token}`
            'Accept'       : 'application/json',
            'Content-Type' : 'application/json',
        },
        body: JSON.stringify({
            cat : cat_value,
        })
    })
    .then((response) => response.json())
    .then((responseData) => { console.log(responseData) })
    .catch((error) => { console.log(error) })
    .done()
    

    Also, it'd be great to see what's the Rails output in the console when you make a request, or the browser console.