使用App Script同步Notion数据至Google表格遇404/401错误求助
问题重现
尝试用以下Google Apps Script脚本更新Notion数据库页面:
function updatePage() { let token = 'secret_hhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh'; let pageId = '77777777777777777777777777777777'; let props = { "properties": { "[The Property Name]": { //in the case of a text field: "rich_text": [{ "text": { "content": "[The New Value!]" }}]}}}; let options = { "method": 'patch', headers: { "Content-Type": "application/json", "Notion-Version": "2022-02-22", "Authorization": "Bearer " + token }, "payload": JSON.stringify(props), "redirect": "follow" }; let url = 'https://api.notion.com/v1/pages/'+pageId; let response = UrlFetchApp.fetch(url,options); Logger.log(JSON.parse(response.getContentText())); }
运行时触发404错误:
Exception: Request failed for https://api.notion.com returned code 404. Truncated server response: {"object":"error","status":404,"code":"object_not_found","message":"Could not find page with ID: 77777777-7777-7777-7777-777777777777. Make sure th... (use muteHttpExceptions option to examine full response)
Page ID取自Notion分享链接的v参数:https://terrific-barnacle-42j.notion.site/aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa?v=77777777777777777777777777777777,直接访问https://api.notion.com/v1/pages/77777777777777777777777777777777返回401错误:
{"object":"error","status":401,"code":"unauthorized","message":"API token is invalid."}
解决方案
1. 修正Page ID的取值
你混淆了页面ID和视图ID:
- 分享链接中,
https://xxx.notion.site/后面的字符串(即aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)才是页面ID v=后面的字符串是视图ID,不是页面本身的ID- 替换脚本中的
pageId为正确的页面ID,Notion API接受带连字符(如77777777-7777-7777-7777-777777777777)或不带连字符的格式
2. 验证API Token的有效性与权限
- 检查
token是否完全正确,注意复制时不要遗漏首尾字符 - 登录Notion,进入设置与成员 > 集成 > 你的集成,确认该集成已被添加到目标页面/数据库中:打开目标页面,点击右上角
...> 添加连接 > 选择你的集成 - 确保Notion版本头
Notion-Version与API要求兼容(当前脚本使用的2022-02-22是有效版本)
3. 优化脚本调试(可选)
在UrlFetchApp.fetch的options中添加"muteHttpExceptions": true,可以查看完整的错误响应,便于定位问题:
let options = { "method": 'patch', "muteHttpExceptions": true, // 添加此行 headers: { "Content-Type": "application/json", "Notion-Version": "2022-02-22", "Authorization": "Bearer " + token }, "payload": JSON.stringify(props), "redirect": "follow" };
内容的提问来源于stack exchange,提问作者Tanatchat Laemkom Film

