typescriptoffice-jsoffice-addinsadd-in

fetch() partially working in office add-in


I am building an office add-in, specifically to be used in Word. I also have an API that I built using Django that accepts and takes in data as 'formData'. Now, in my office add-in I have written a function with a custom fetch request:

 const response = await fetch('http://127.0.0.1:8000/api/v1/my-upload-api', {
      method: 'POST',
      body: formData
  });

When the code runs the API is getting called, my other backend also functions fine and uploads the file, but here in the add-in code, it throws TypeError: Failed to fetch. I tried adding debuggers and log statements after the fetch request, but it throws the TypeError (lineNumber: 30) so it goes directly into the catch block. I also tried handling the response through promises like this:

const response = await fetch('http://127.0.0.1:8000/api/v1/upload-contracts', {
      method: 'POST',
      body: formData
  }).then((response) =>{
    response.json().then(result => {
      console.log(result);
      return result;
    });  
  });

But this didn't work either. I can really use some help here. Thanks!


Solution

  • I figured out that, if you've generated the project template using Yoman's yo office with TypeScript support, then by default the initialized project tries to access localhost:3000 over https. Because of this, it fails to find the compiled JavaScript file(s).

    Solution While running the Add-in locally in dev mode, replace all the https://localhost:3000 calls to http://localhost:3000. You can also set https dynamically throughout the project using environment variables. This is kind of a hacky way to solve the problem, but it works flawlessly.