如何在 excel 网络插件中发送 http 请求?

how to send a http resquest in excel web addin?

我正在使用 SSL 证书通过 javascipt 创建一个 excel 网络插件。

现在我想发送一个 get-resquest (http) 来获取数据。(不是 https)

我找到这篇文章: https://docs.microsoft.com/en-us/office/dev/add-ins/develop/addressing-same-origin-policy-limitations 但是我还是不会写代码,有demo吗?

function getdata() {
  Excel.run(function(context) {   

    if(document.getElementById("theniubikey")) {
      head.removeChild(script); //删除临时添加的script标签
    }
   
    var script = document.createElement("script");
    script.type = "text/javascript";
    script.id = "theniubikey";
    var url="http://127.0.0.1/api/getdata/10001";
    script.setAttribute(
      "src",
      url + "?alt=json-in-script&callback=jsonpCallback"
    );   
    document.getElementsByTagName("head")[0].appendChild(script);
    // return context.sync();
     return context.sync().then(
      (window.jsonpCallback = function(data) {
        
       //document.getElementById("textareaid").innerHTML = data.length();
       document.getElementById("textareaid").innerHTML =  JSON.stringify(data);

        return data;
      })
    );
    
    
  }).catch(function(error) {
    console.log("Error: " + error);
    if (error instanceof OfficeExtension.Error) {
      console.log("Debug info: " + JSON.stringify(error.debugInfo));
    }
  });
}

我想如果cors失败,在开发者工具中,它会显示错误信息。也许你可以去看看细节。

我建议你使用 fetch API 在 addin 中查询数据:

  function getdata() {
    Excel.run(async function (context) {
      const resp = await fetch('http://127.0.0.1/api/getdata/10001');
      document.getElementById("textareaid").innerHTML = await resp.text();
    }).catch(function (error) {
      console.log("Error: " + error);
      if (error instanceof OfficeExtension.Error) {
        console.log("Debug info: " + JSON.stringify(error.debugInfo));
      }
    });
  }

同时,您需要 return header Access-Control-Allow-Origin: <your-addin-http-origin> 在您的 http://127.0.0.1/api/getdata/10001 的本地主机服务器响应中。 (否则 fetch 将因 cors 而失败。)

这个header的详细用法可以参考Access-Control-Allow-Origin - HTTP | MDN (mozilla.org)

Office Add-In 中的 http 个请求有两个选项。

选项 1:

  • 如果您在 http url 上托管 add-in,您可以在 http.
  • 中提出请求
  • 注意:这不能提交给 MS,因为他们需要 https,但可以通过自助服务选项(内部使用)使用。

选项 2:

  • 安装 API 网关,例如 krakend
  • 这样你的 add-in 在 Excel 和服务器 [Krakend] 之间进行 100% https 对话,服务器通过 http 处理请求。
  • 可能有一种方法可以通过远程服务器代理所有内容,但如果 add-in 通过 https 托管,则基本上 Excel 和服务器之间需要 https