使用Google Sheets API refresh token调用update方法更新单元格报401错误
问题修复方案
你的401未授权错误由代码中的3处核心配置错误导致,按以下步骤修改即可:
1. 修正API请求端点
你当前写的请求URL存在3个问题:
- 写入单元格属于
values:update操作,路径拼接错误,且错误使用&作为路径和查询参数的分隔符(正确分隔符为?) - 使用OAuth2 Bearer Token鉴权时不需要携带API Key,同时传递两种鉴权凭据会触发鉴权冲突
- 缺少必填查询参数
valueInputOption,该参数用于指定写入值的解析规则
修正后的URL格式如下:
https://sheets.googleapis.com/v4/spreadsheets/{替换成你的表格ID}/values/A1?valueInputOption=RAW
其中valueInputOption=RAW表示直接写入原始字符串,不对内容做公式、格式自动解析。
2. 修正请求方法和无效请求头
- 单元格更新接口要求使用
PUT方法,你当前用的POST方法不符合接口规范 Access-Control-Allow-Origin是服务端返回的响应头,前端发起请求时不需要携带该头,多余配置会触发跨域预检异常,直接删除这行设置即可。
3. 修正函数传参逻辑
你调用SheetRequest时仅传入了access_token一个参数,但函数签名声明需要接收callback、request参数,函数内部虽重写了request变量,但回调参数缺失会导致请求成功后抛出undefined错误,可直接简化函数逻辑,去掉无用的参数声明。
修正后可直接运行的代码
function get_access_token_using_saved_refresh_token() { const refresh_token = "INSERT REFRESH TOKEN"; const client_id = "INSERT CLIENT ID"; const client_secret = "INSERT CLIENT KEY"; const refresh_url = "https://www.googleapis.com/oauth2/v4/token"; const post_body = `grant_type=refresh_token&client_id=${encodeURIComponent(client_id)}&client_secret=${encodeURIComponent(client_secret)}&refresh_token=${encodeURIComponent(refresh_token)}`; let refresh_request = { body: post_body, method: "POST", headers: new Headers({ 'Content-Type': 'application/x-www-form-urlencoded' }) } fetch(refresh_url, refresh_request).then( response => { return response.json(); }).then( response_json => { console.log('获取access token成功', response_json); SheetRequest(response_json.access_token); }); } function SheetRequest(access_token){ // 替换为正确的请求URL var url = 'https://sheets.googleapis.com/v4/spreadsheets/{INSERT SHEETID}/values/A1?valueInputOption=RAW'; var requestBody = { "majorDimension": "ROWS", "values": [ ["test"] ] }; var xhr = new XMLHttpRequest(); xhr.open("PUT", url); xhr.setRequestHeader('Authorization', 'Bearer ' + access_token); xhr.setRequestHeader('Content-Type', 'application/json'); xhr.onload = function () { if (xhr.readyState === 4) { if (xhr.status === 200) { console.log('写入成功', xhr.responseText); } else { console.log('请求失败,状态码:', xhr.status, '错误信息:', xhr.responseText); } } }; xhr.send(JSON.stringify(requestBody)); } get_access_token_using_saved_refresh_token();
额外排查项(如果修改后仍报401)
- 确认用refresh token换取access token时,申请的权限范围包含
https://www.googleapis.com/auth/spreadsheets,仅只读权限无法执行写入操作 - 确认你使用的Google Cloud项目已启用Google Sheets API
- 确认OAuth凭据对应的账号(个人账号/服务账号)对目标表格拥有编辑权限
内容的提问来源于stack exchange,提问作者Le Wolf
相关产品推荐
相关产品推荐

