如何在 Office JS Excel-Add-In 的自定义函数中使用令牌授权请求数据?

How to request data with token authorization in custom functions in Office JS Excel-Add-In?

我有:

我改编了 Microsoft 文档中的 this 示例。

// functions.js

/**
 * Get data
 * @customfunction
 *  @returns {string[][]}
 */
async function getData() {
  try {
    const url = "https://api.example.com/some/objects/";
    const token = await OfficeRuntime.storage.getItem("Token");
    const authString = `Token ${token.toString()}`;
    const response = await fetch(url, {
      headers: { Authorization: authString }
    });

    if (!response.ok) {
      throw new Error(response.statusText);
    }
    const jsonResponse = await response.json();

    return jsonResponse.map(obj => {return [obj.id.toString(), obj.name]};
  } catch (error) {
    return [["ERROR", error.message]];
  }
}

我得到的:

因为它不是本地开发的,所以很难调试 ui-less 自定义函数。因此,到目前为止,我得到的唯一可见错误是我收到的错误以及 catch 块中的 return 到 Excel。这是一条无用的错误消息:Network request failed

谁能帮我提点建议?

它不起作用的原因是一个已知问题,即自定义函数 运行 在单独的 JavaScript 运行 时间中描述 here。这个 运行time 只允许 CORS-safelisted 请求 header 因为它缺少 CORS-Preflight -> 因此 Network request failed 错误 Authorization header.

我是怎么解决的:

  1. 配置 Excel-Add-in 以使用共享的 JavaScript 运行 时间 here
  2. taskpane.html 中的 <\head> 元素之前添加 <script src="functions.js"></script>,如 here 所述。
  3. 构建项目npm run build
  4. 按照前两个步骤here所述清除缓存。

运行 Excel 并加载您的 Add-in.