0

I am creating an excel web addin by javascipt with in SSL certificate.

now I want to send a get-resquest (http) to get data.(not https)

I found this article: https://learn.microsoft.com/en-us/office/dev/add-ins/develop/addressing-same-origin-policy-limitations but I still don't know how to code,are there some demos?

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));
    }
  });
}
kedouwen
  • 5
  • 2

2 Answers2

1

I think if the cors failed, in the developer tool, it will show the error message. Maybe you can check it out to see the detail.

I suggest you to use the fetch API to query data in 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));
      }
    });
  }

At the same time, you need to return the header Access-Control-Allow-Origin: <your-addin-http-origin> in your localhost server response of http://127.0.0.1/api/getdata/10001. (Otherwise the fetch will fail due to the cors.)

The detail usage of this header can be found Access-Control-Allow-Origin - HTTP | MDN (mozilla.org).

CI010
  • 38
  • 3
1

There are two options for http requests in an Office Add-In.

Option 1:

  • If you host the add-in on http url, you can make requests in http.
  • Note: This can't be ever submitted to MS as they require https, but can be used via self serve options (internal use).

Option 2:

  • Install an API Gateway such as krakend
  • This way your add-in talks 100% https between Excel and Server[Krakend] and the server does the request over http.
  • There likely is a way to just proxy everything over your remote server, but you basically need https between Excel and Server if add-in is hosted via https
FreeSoftwareServers
  • 2,271
  • 1
  • 33
  • 57