Adding jwt token to GET request not working in React

Adding jwt token to GET request not working in React
0

#1

Hello, I really need some help on a problem I’ve been stuck on for a while. 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. It also console.logs correctly in componentDidMount code lines. But when I try to add it in my API call I am getting the error no jwt found. Any help would be appreciated. Thanks !


import React from 'react';

const url = 'https://url';

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() {
    let auth =  localStorage.getItem('user_token');
     console.log(auth);
     this.getData(auth);
  }

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

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

}