'Fetch Post request not working in Custom functions Office Addin [TypeError: Network request failed]

I having been facing this error in custom functions excel Add-in, where I'm trying to call an external service inside a custom function. It works fine for a GET request such as this:

function stockPrice(ticker) {
var url = "https://api.iextrading.com/1.0/stock/" + ticker + "/price";
return fetch(url)
    .then(function(response) {
        return response.text();
    })
    .then(function(text) {
        return parseFloat(text);
    });
}

CustomFunctionMappings.STOCKPRICE = stockPrice;

Taken from https://docs.microsoft.com/en-us/office/dev/add-ins/excel/excel-tutorial-custom-functions#create-a-custom-function-that-requests-data-from-the-web

But gives an exception for a POST request like this:

function stockPrice(ticker) {
var url = "https://westcentralus.api.cognitive.microsoft.com/text/analytics/v2.0/sentiment";
return fetch(url, {
        method: 'POST',
        headers: {
            'Ocp-Apim-Subscription-Key': key,
            'Content-Type': 'application/json',
            'Accept': 'application/json'
        },
        body: JSON.stringify(body))
    .then(function(response) {
        return response.json();
    })
    .then(function(response) {
        return response.somevalue;
    })
    .catch(e => {
        console.error("Caught exception");
        return JSON.stringify(e);
     });
}

The above is just a sample to have an idea, of how I'm calling my service. I have tried it with 2-3 different services, and I figured out that after running fetch, the code goes to catch block, and the error value that is returned in the excel is an empty object '{}'. Since there are no ways to debug custom functions on windows, and since there is no specific error description, I'm unable to figure out the issue. I have also added my service domain to App Domain list in manifest file but still no effect.



Solution 1:[1]

I am not sure that particular API accepts POST requests, so you maybe running into that.

Debugging in Windows is still being worked on but you can use Excel online and F12tools to debug.

If you are on Windows, you can console.log statements in conjunction with the Runtime logging: https://docs.microsoft.com/en-us/office/dev/add-ins/excel/custom-functions-best-practices#troubleshooting

Hope that helps and we will update this when debugging is ready on for custom functions on windows desktop.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Keyur Patel - MSFT