3

I am trying to run a post request from office scripts on an api, but kept getting a failed to fetch error each time when I add : "Content-type": "application/json" to the header, once I remove the content-type option or replace its value with something other than "application/json" , then the fetch request works , but returns an error with code 0 and validation error messages indicating that the userName and password ('which are already defined in the body could not be found'): Below is the code

    async function main(workbook: ExcelScript.Workbook) {

    const param = {
      method: "POST",
      headers: {
        //"Content-type": "application/json"
      },
      body: JSON.stringify({ user_id: "uname", password: "pwd"})
   
    };

  await fetch("https://testAPI/login/", param).then(response => response.json())
    .then(data => console.log(data));
  }

error when I run this code with Content-Type header set to 'application/json' (line 33 contains the fetch instruction ):

Line 33: Failed to fetch

Error when I run this code with content-Type set to 'text/plain', other options or completely removing the content-type property from the header :

enter image description here

Also , this same request from postman or power automate with header content-type set to 'application/json' runs successfully , the issue happens only in office script

VLAZ
  • 26,331
  • 9
  • 49
  • 67
Ferhi Malek
  • 484
  • 4
  • 15
  • There's a section called "Limitations with external calls from Office Scripts" on Microsoft Docs. Do you know if you're running into any of those? You can read that here: https://learn.microsoft.com/en-us/office/dev/scripts/develop/external-calls – Brian Gonzalez Mar 03 '22 at 20:38

1 Answers1

0

The issue could potentially have to do with CORS. I had to include CORS headers on the API endpoint I was trying to hit. This may be the issue since you said the status code of the response was 0. Why fetch return a response with status = 0?

I added the following headers to the API route:

Access-Control-Allow-Origin: *
Access-Control-Allow-Methods: GET, POST, OPTIONS
Access-Control-Allow-Headers: Content-Type, Authorization, X-Requested-For

Here is my OfficeScript code for reference:

const response = await fetch(url, {
    method: 'POST',
    body: JSON.stringify(cellData),
    headers: {
        'Content-Type': 'application/json'
    }
})
noahtk7
  • 26
  • 3
  • 1
    `response.json()` should be awaited and `response.body` is a stream, so I would use `response.text()` instead (which also needs to be awaited). However, it's hard to tell if `response.body` and `response.json()` "not return[ing] anything" is relevant to answering this question. I also fail to see how the very first line is relevant to the answer. Please edit your answer accordingly. – Jesse Sep 13 '22 at 23:59