简体   繁体   中英

set token in authorization header

I want to set token in authorization header but the token is set null. I tried to get the token from chrome storage but token is not set though i get the token from the storage when i console the result['user_token'] inside the callback.

here is the code

var token = null; // i need this token in fetchTopics as well
function fetchCurrentUser() {
  const apiUrl = `api2.navihq.com/get_current_user`;
  chrome.storage.sync.get(['user_token'], function(result) {
    token = result['user_token'];
  });
  console.log('token', token); // getting null
  const headers = new Headers();
  headers.append('Content-Type', 'application/json');
  headers.append('Authorization', `Token: ${token}`)
  fetch(apiUrl, {
    method: 'GET',
    headers
  })
  .then(function(response) {
    console.log('response', response);
    return response.json()
  })
  .then(function(data) {
    console.log('data', data);
    return JSON.parse(atob(data.user))
  })
}


$(window).bind('load', function() {
    document.addEventListener('click', init);
  fetchCurrentUser();
  fetchTopics();
});

How do i now set the token in authorization header?

The sync in chrome.storage.sync.get doesn't mean it's synchronous

the fact it takes a callback shows it is A synchronous - not that taking a callback guarantees something is asynchronous of course, but in this case it's clear that it is

So put the fetch inside the callback

function fetchCurrentUser() {
    const apiUrl = `api2.navihq.com/get_current_user`;
    chrome.storage.sync.get(['user_token'], function(result) {
        var token = result['user_token'];
        console.log('token', token); // getting null
        const headers = new Headers();
        headers.append('Content-Type', 'application/json');
        headers.append('Authorization', `Token: ${token}`)
        fetch(apiUrl, {
            method: 'GET',
            headers
        }).then(function(response) {
            console.log('response', response);
            return response.json()
        }).then(function(data) {
            console.log('data', data);
            return JSON.parse(atob(data.user))
        })
    });
}

Alternatively you can "promisify" the chrome.storage.sync.get function

function fetchCurrentUser() {
    const chromeStorageGetPromise = key => 
        new Promise(resolve => chrome.storage.sync.get(key, resolve));

    const apiUrl = `api2.navihq.com/get_current_user`;
    chromeStorageGetPromise(['user_token'])
    .then(({user_token: token}) => {
        console.log('token', token);
        const headers = new Headers();
        headers.append('Content-Type', 'application/json');
        headers.append('Authorization', `Token: ${token}`);
        return fetch(apiUrl, {
            method: 'GET',
            headers
        });
    }).then(response => {
        console.log('response', response);
        return response.json();
    }).then(data => {
        console.log('data', data);
        return JSON.parse(atob(data.user));
    })
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM