使用Fetch调用Google Sheets API v4获取数据时收到401错误,请求排查原因
The Problem
I'm trying to fetch data from my Google Sheet using the Fetch API with Google Sheets API v4 via a GET request to https://sheets.googleapis.com/v4/spreadsheets/{spreadsheetId}. Here's my code:
let fetch_url = "https://sheets.googleapis.com/v4/spreadsheets/1UOaYEl8i33Bco5PaIXAljWkPFmt3j3i1tohXwNl3vvs?key=" + apiKey let fetch_option = { method: 'GET', headers: { Authorization: `Bearer ${accessToken}`, 'Content-Type': 'application/json' } } fetch(fetch_url,fetch_option) .then(res => function(res){ console.log(res.JSON()) })
But I'm getting a 401 error when running this Fetch function. Here's my extension's permissions and OAuth2 config:
"permissions":[ "activeTab", "identity", "http://*/" ], "background":{ "scripts":["src/script/background.js","src/script/jsrsasign-all-min.js"], "persistent": false }, "oauth2": { "client_id": "Client ID", "scopes":["https://www.googleapis.com/auth/spreadsheets", "https://sheets.googleapis.com/v4/spreadsheets/*"] }
Let's Fix the 401 Error
Here are the key issues causing your error and their fixes:
1. Invalid OAuth2 Scopes
Your scopes include an incorrect, non-standard entry: https://sheets.googleapis.com/v4/spreadsheets/*. Google Sheets API uses top-level OAuth scopes, not endpoint-specific paths. Remove this invalid line—stick to official scopes only. Use https://www.googleapis.com/auth/spreadsheets for read-write access, or https://www.googleapis.com/auth/spreadsheets.readonly if you only need to view data (more secure for read-only use cases).
Updated oauth2 config:
"oauth2": { "client_id": "Your Actual Client ID", "scopes":["https://www.googleapis.com/auth/spreadsheets"] }
2. Broken Fetch Response Handling
Your .then() callback has two critical mistakes:
- You're wrapping the response handler in an extra unnecessary anonymous function
res.JSON()is a typo—Google's Fetch API uses lowercaseres.json()
Fixed fetch code with error handling added:
let fetch_url = "https://sheets.googleapis.com/v4/spreadsheets/1UOaYEl8i33Bco5PaIXAljWkPFmt3j3i1tohXwNl3vvs"; let fetch_option = { method: 'GET', headers: { Authorization: `Bearer ${accessToken}`, 'Content-Type': 'application/json' } }; fetch(fetch_url, fetch_option) .then(res => { if (!res.ok) throw new Error(`HTTP error! Status: ${res.status}`); return res.json(); }) .then(data => console.log("Fetched sheet data:", data)) .catch(err => console.error("Fetch failed:", err));
3. Conflicting Authentication Methods
You're including both an API key in the URL and a Bearer token in the headers—Google APIs only accept one authentication method at a time. Since you're using OAuth2 to access private sheet data, remove the API key from the URL entirely.
4. Incomplete Manifest Permissions
The http://*/ permission is overly broad and doesn't cover HTTPS endpoints (Google Sheets API uses HTTPS exclusively). Replace it with the specific HTTPS URL for the Sheets API to ensure your extension has proper request permissions:
"permissions":[ "activeTab", "identity", "https://sheets.googleapis.com/*" ]
Additional Checks
- Double-check that your OAuth2 client ID in the manifest matches the one configured in the Google Cloud Console, and that your extension's ID is added as an authorized JavaScript origin there.
- Verify your
accessTokenis valid and not expired. Use Chrome'sidentity.getAuthToken()method to retrieve a fresh, valid token within your extension's background or content scripts.
内容的提问来源于stack exchange,提问作者new guy

