You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Fetch调用Google Sheets API v4获取数据时收到401错误,请求排查原因

401 Unauthorized Error When Fetching Google Sheets API v4 Data with Chrome Extension OAuth2

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 lowercase res.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 accessToken is valid and not expired. Use Chrome's identity.getAuthToken() method to retrieve a fresh, valid token within your extension's background or content scripts.

内容的提问来源于stack exchange,提问作者new guy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.30 12:47:50