使用Google Auth与createIfNotExist无法向Sanity后端提交数据
解决Sanity createIfNotExist提交失败问题
以下是针对你的问题的排查和修复方案:
1. 检查Sanity客户端写入权限
createIfNotExist属于写入操作,必须确保你的Sanity客户端配置了带write权限的token,公共只读客户端无法完成提交。
import { createClient } from '@sanity/client' const client = createClient({ projectId: '你的项目ID', dataset: '你的数据集', apiVersion: '2024-01-01', // 使用较新版本API token: '带write权限的token', // 关键:必须配置写入权限token useCdn: false // 写入操作禁用CDN })
2. 验证文档结构与Schema匹配
确认Sanity后台users类型的Schema定义,字段名、类型必须和你提交的doc完全一致:
- 比如
userName需对应Schema中的string类型字段,image如果是URL则需对应url类型,若为Sanity资产则需用image类型。
示例Schema参考:
export default { name: 'users', type: 'document', fields: [ { name: 'userName', type: 'string', title: '用户名' }, { name: 'image', type: 'url', title: '头像URL' } ] }
3. 完善错误捕获逻辑
当前代码的try/catch无法捕获createIfNotExist的异步错误,改用async/await可以统一捕获所有异常,方便定位问题:
const responseGoogle = async (response: any) => { localStorage.setItem( "user", JSON.stringify(jwt_decode(response.credential)) ); try { const decode: { name: string; picture: string; sub: string } = jwt_decode(response.credential); const { name, picture, sub } = decode; const doc = { _id: sub, _type: "users", userName: name, image: picture, }; await client.createIfNotExist(doc); navigate("/", { replace: true }); } catch (error) { console.error('Sanity提交失败详情:', error); // 控制台会输出具体错误原因 } };
4. 检查_id格式合法性
Sanity文档_id仅支持小写字母、数字、连字符、下划线和点,若Google返回的sub包含特殊字符,需先处理后再作为_id使用,比如:
const validId = sub.replace(/[^a-z0-9\-_.]/gi, ''); const doc = { _id: validId, // ...其他字段 };
5. 确认API版本兼容性
createIfNotExist是Sanity较新的API方法,确保客户端配置的apiVersion为最近的日期(如2024-01-01),避免因版本过低导致方法不支持。
内容的提问来源于stack exchange,提问作者Wahab Mufidat
相关产品推荐
相关产品推荐

