在授权标头中设置令牌

时间:2018-05-31 05:20:49

标签: javascript google-chrome google-chrome-extension

我想在授权标头中设置令牌,但令牌设置为null。我尝试从chrome存储中获取令牌但是虽然我在回调中控制result['user_token']时从存储中获取令牌,但未设置令牌。

这是代码

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();
});

我现在如何在授权标头中设置令牌?

1 个答案:

答案 0 :(得分:3)

sync中的chrome.storage.sync.get并不意味着它是同步的

需要回调的事实表明它是 A 同步 - 而不是采取回调保证某些东西当然是异步的,但在这种情况下它很清楚它是

所以把提取放在回调

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))
        })
    });
}

或者你可以" promisify" chrome.storage.sync.get函数

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));
    })
}