我想在授权标头中设置令牌,但令牌设置为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();
});
我现在如何在授权标头中设置令牌?
答案 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));
})
}