1

React newbie here, but proficient in Django.I have a simple fetch function which worked perfectly but then my project had no login authentication involved. Now that I have configured the login system, my backend refuses to serve requests with any access tokens. My login authentication is very new to me and was more or less copied from somewhere. I am trying to understand it but am not able to. I just need to know how to convert my simple fetch function to include the getAccessToken along the request in it's headers so my backend serves that request.

Here is my previously working simple fetch function :

class all_orders extends Component {
  state = {
    todos: []
  };

  async componentDidMount() {
    try {
      const res = await fetch('http://127.0.0.1:8000/api/allorders/'); // fetching the data from api, before the page loaded
      const todos = await res.json();
      console.log(todos);
      this.setState({
        todos
      });
    } catch (e) {
      console.log(e);
    }
  }

My new login JWT authentication system works perfectly, but my previous code is not working and I keep getting error

"detail": "Authentication credentials were not provided."

This is is the accesstoken I am not able to 'combine' with my preivous fetch function:

const getAccessToken = () => {
    return new Promise(async (resolve, reject) => {
        const data = reactLocalStorage.getObject(API_TOKENS);

        if (!data)
            return resolve('No User found');

        let access_token = '';
        const expires = new Date(data.expires * 1000);
        const currentTime = new Date();

        if (expires > currentTime) {
            access_token = data.tokens.access;
        } else {
            try {
                const new_token = await loadOpenUrl(REFRESH_ACCESS_TOKEN, {
                    method: 'post',
                    data: {
                        refresh: data.tokens.refresh,
                    }
                });
                access_token = new_token.access;
                const expires = new_token.expires;

                reactLocalStorage.setObject(API_TOKENS, {
                    tokens: {
                        ...data.tokens,
                        access: access_token
                    },
                    expires: expires
                });

            } catch (e) {
                try {
                    if (e.data.code === "token_not_valid")
                        signINAgainNotification();
                    else
                        errorGettingUserInfoNotification();
                } catch (e) {
                    // pass
                }

                return reject('Error refreshing token', e);
            }
        }

        return resolve(access_token);
    });
};
Rohit Kumar
  • 684
  • 2
  • 17
  • 39

1 Answers1

1

If you're looking for a way how to pass headers in fetch request, it's pretty straight forward:

await fetch('http://127.0.0.1:8000/api/allorders/', {
 headers: {
   // your headers there as pair key-value, matching what your API is expecting, for example:
   'details': getAccessToken()
  }
})

Just don't forget to import your getAccessToken const, if that's put it another file, and I believe that would be it. Some reading on Fetch method

Adam Kosmala
  • 925
  • 6
  • 9
  • I tried defining the whole `getAccessToken` in the same file so I could use it without importing, I got this error `Unhandled Rejection (Error): Actions must be plain objects. Use custom middleware for async actions.` – Rohit Kumar Aug 08 '19 at 11:46
  • This error is redux related, as far as I know, as if getAccessToken method is redux action. Are you using it? – Adam Kosmala Aug 08 '19 at 12:36
  • I am though, I do not thoroughly understand it...I am trying to scale somebody else's code – Rohit Kumar Aug 08 '19 at 12:39
  • Hey, I just found out my headers is still being sent as empty. Any idea why this might be ? I have tried importing the variable or even defining it in the same file. I get no error at all, but the headers being sent is empty. – Rohit Kumar Aug 08 '19 at 12:57
  • Try debugging the `getAccessToken` function step by step in order to see what's going on there exactly – Adam Kosmala Aug 08 '19 at 13:37