为什么无法将变量作为URL传入Planner Task的reference参数?
问题原因及解决方法
1. 动态对象键语法错误
你的代码中直接把encodedLink作为对象的键名,JavaScript会默认将其识别为字符串"encodedLink",而非读取encodedLink变量的实际值作为键。硬编码时你直接传入了编码后的URL字符串作为键,因此可以成功。
要使用变量作为对象键,需要使用计算属性语法,用方括号包裹变量名:[encodedLink]。
2. 批量更新逻辑错误
你在forEach循环中为每个链接单独调用一次更新接口,存在两个问题:
forEach不支持async/await的顺序等待,多个异步请求会并发触发- 第一次更新成功后,Planner任务的etag会自动变更,后续请求使用旧的etag会触发412前置条件失败错误
正确做法是先将所有链接一次性组装到references对象中,仅调用一次更新接口。
修正后的代码示例
const updateAttachedFiles = async ( links: string[], taskId: string, etag: string ) => { // 先组装所有reference const references = {}; links.forEach(link => { const encodedLink = escapeHtml(link); // 用计算属性设置动态键 references[encodedLink] = { "@odata.type": "microsoft.graph.plannerExternalReference", "previewPriority": " !", type: "Other", }; }); // 仅调用一次更新接口 await graph.planner.tasks.getById(taskId).details.update( { references }, etag ); }; const escapeHtml = (unsafe: string) => { // 补充官方要求的编码字符,可根据实际场景调整 return unsafe .replaceAll("%", "%25") .replaceAll(".", "%2E") .replaceAll(":", "%3A") .replaceAll("@", "%40") .replaceAll("#", "%23") .replaceAll("/", "%2F") .replaceAll(" ", "%20") .replaceAll("?", "%3F"); }
内容的提问来源于stack exchange,提问作者Magdalena Fernlund
相关产品推荐
相关产品推荐

