Chrome存储获取token后Authorization header赋值为null的解决方法
Ah, I see the issue here—this is a classic asynchronous operation timing problem! Let me break it down and show you how to fix it.
The Root Cause
chrome.storage.sync.get is an asynchronous function. When you call it, your code doesn't wait for the callback to finish before moving on to the console.log and fetch call. By the time you try to use the token variable in your Authorization header, the callback that sets token = result['user_token'] hasn't run yet—so token is still its initial null value.
Solution 1: Move Fetch Logic Inside the Callback
The simplest fix is to move all code that depends on the token inside the chrome.storage.sync.get callback. This ensures you only use the token after it's been retrieved:
var token = null; 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); // Now this will show the valid token 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(); // Wait—fetchTopics also needs the token! See Solution 2 for a better approach });
Solution 2: Use Async/Await for Cleaner Code (Recommended)
Since you need the token for both fetchCurrentUser and fetchTopics, wrapping the storage call in a promise and using async/await will make your code more readable and ensure both functions have access to the token before running:
// Helper function to get token as a promise function getToken() { return new Promise((resolve, reject) => { chrome.storage.sync.get(['user_token'], function(result) { if (result.user_token) { resolve(result.user_token); } else { reject(new Error('No token found in storage')); } }); }); } async function fetchCurrentUser(token) { const apiUrl = `api2.navihq.com/get_current_user`; const headers = new Headers(); headers.append('Content-Type', 'application/json'); headers.append('Authorization', `Token: ${token}`); const response = await fetch(apiUrl, { method: 'GET', headers }); const data = await response.json(); console.log('response', response); console.log('data', data); return JSON.parse(atob(data.user)); } async function fetchTopics(token) { // Use the token here in your fetchTopics logic console.log('Using token in fetchTopics:', token); // ... your existing fetchTopics code } $(window).bind('load', async function() { document.addEventListener('click', init); try { // Wait for the token to be retrieved first const token = await getToken(); // Now run both functions with the valid token await fetchCurrentUser(token); await fetchTopics(token); } catch (error) { console.error('Error during token retrieval or API calls:', error); } });
This approach guarantees that token is available before either fetchCurrentUser or fetchTopics execute, eliminating the null value issue entirely.
内容的提问来源于stack exchange,提问作者milan

