Milda Nor
Milda Nor

Reputation: 71

Adding jwt token to GET request not working in React

in order to get data from an API, I need to send a jwt token in the header of the call. I save it in local storage after I get it in my application and when I check in the console of the browser, I can see that saving it works - I can see it appear in the console when I do localStorage.getItem('token') there. But when I try to add it in my API call I am getting the error no jwt found. Clearly the get request is being executed before my logic for getting them token from local storage is executed.. Below is my code. Any advice on how to get around this would be appreciated. Thanks !

const url = 'https://url.com';
const token = localStorage.getItem('token');
const AuthStr = 'Bearer '.concat(token);

export default class TestCall extends React.Component {
constructor(props) {
    super(props);
    this.state = {
      error: undefined,
      isLoaded: false,
      items: [],
    };

   this.getData = this.getData.bind(this);
  }
  componentDidMount() {
    this.getData();
  }

  getData () {
  return fetch(url, {
    method: 'GET',
    headers:{
      Accept: 'application/json',
               'Content-Type': 'application/json',
       },
           Authorization: "Bearer " + AuthStr,
  })
      .then(res => res.json())
      .then(
        (result) => {

          this.setState({
            isLoaded: true,
            items: result
          });
        },
        (error) => {
          this.setState({
            isLoaded: true,
            error
          });
        }
      )
  }


  render() {
    const { error, isLoaded, items } = this.state;
    if (error) {
      return <div>Error: {error.message}</div>;
    } else if (!isLoaded) {
      return <div>Loading...</div>;
    } else {
      return (
       <p>{items} </p>
      );
    }
  }

}

UPDATE:

as per the answer I received I changed my code at the top to:

const token = localStorage.getItem('token');

I deleted the const AuthStr. so my get request now is:

headers:{
Accept: 'application/json',
         'Content-Type': 'application/json',
       },
           Authorization: "Bearer " + token,
  })

This should have fixed the typo but the response I am getting is still no jwt found.

Upvotes: 1

Views: 8594

Answers (2)

Milda Nor
Milda Nor

Reputation: 71

Thanks for trying to help me to get this to work @Yoav!

However, seems that the problem was elsewhere - I was not adding the token in the correct place in my fetch request.

the code that worked was this:

getData(){
let auth =  localStorage.getItem('user_token');
      return fetch(url, {
       method: 'GET',
       headers:{
         Accept: 'application/json',
                  'Content-Type': 'application/json',
                  'Authorization': "Bearer " + auth,
          },
     })
         .then(res => res.json())

I can even define auth variable and get the token in the function just before executing fetch - calling it in componentdidmount also worked but that not the main issue.

For anyone else working on this watch where you are putting the token in the request !

Upvotes: 2

Yoav
Yoav

Reputation: 3386

it seems that when initialize the const AuthStr you're already adding the Bearer string to it :
const AuthStr = 'Bearer '.concat(token);.
then, when setting up the request you're doing it again:
Authorization: "Bearer " + AuthStr.
so what you're actually sending looks like this: Bearer Bearer your token.
have you tried instantiating the AuthStr parameter inside the getData() function or componentDidMount()?

Upvotes: 2

Related Questions