在Word Office插件中初始化pnpjs/graph失败,求示例代码
PnPjs Graph 初始化示例及问题排查
正确的初始化代码示例
import { graphfi, GraphFI } from "@pnp/graph"; import { DefaultInit } from "@pnp/graph/behaviors"; class YourService { private graph: GraphFI; private authority: string; // 格式:https://login.microsoftonline.com/{租户ID/域名} constructor(private authService: YourAuthService) { this.initGraph(); } private initGraph(): void { this.graph = graphfi().using( DefaultInit(), (instance) => { instance.on.auth.replace(async (url, init) => { const tokenResult = await this.authService.getGraphApiToken({ authority: this.authority }); if (!tokenResult?.accessToken) { throw new Error("未获取到有效访问令牌"); } init.headers = { ...init.headers, Authorization: `Bearer ${tokenResult.accessToken}` }; return [url, init]; }); } ); } public async testTokenValidity(): Promise<void> { try { const result = await this.graph.me(); console.log("testTokenValidity: ", result); } catch (error) { console.error("令牌验证失败: ", error); } } }
问题排查要点
- 返回值格式错误:你原代码的返回语句写法不规范,
return c.headers = {...}, [s, c]这种逗号表达式容易导致逻辑错误。必须明确返回[url, init]数组,确保认证后的请求参数正确传递。 - 令牌权限不足:调用
graph.me()需要User.Read权限;访问SharePoint文档库则需要Files.Read或Sites.Read.All等权限。检查你的令牌是否包含所需权限。 - Authority配置错误:确认
this.authority格式正确,必须是租户对应的授权地址,例如https://login.microsoftonline.com/contoso.onmicrosoft.com。 - 令牌有效性验证:解码返回的accessToken,查看其有效范围(scp字段)和过期时间(exp字段),确认令牌未过期且权限匹配。
- 依赖版本兼容:确保
@pnp/graph及相关依赖包版本一致,避免版本冲突引发初始化异常。
读取SharePoint文档库JSON文件示例
初始化成功后,可通过以下代码读取目标JSON文件:
public async getSharePointJson(siteId: string, driveId: string, filePath: string): Promise<any> { try { const fileContent = await this.graph.sites.getById(siteId) .drives.getById(driveId) .root.itemWithPath(filePath) .content(); return JSON.parse(await fileContent.text()); } catch (error) { console.error("读取SharePoint JSON文件失败: ", error); throw error; } }
内容的提问来源于stack exchange,提问作者Frank Link
相关产品推荐
相关产品推荐

