TypeError: fetch is not a function when running Client Script in ServiceNow

Viewed 426

I am working on an application in ServiceNow where I have the following UI:

service now UI

I have to make a POST request when Submit is pressed. Till now I have got the following lead to make a request.

You can use the native Fetch API to make arbitrary HTTP calls, or you can use the helpers.snHttp method if you are going to be making API calls to your own ServiceNow instance

The Fetch API looks like something that I need here. When I try to run the following script, I get an error.
Script:

function sendRequest() {
    var test = '';
    try{ fetch('https://dummyjson.com/products/1')
        .then(res => res.json())
        .then(json => test = json);
    }catch(e){return e;}
    return test;
}

Error
TypeError: fetch is not a function

I am not finding a way to get rid of this error. I am totally new to ServiceNow scripting. Is there anything I am missing out on?

update 1
enter image description here

2 Answers

I'm not very familiar with serviceNow, but it looks like the fetch function is not supported in the serviceNow javascript engine.

I think you have 2 options:

  1. You can implement by yourself the fetch function and store it on the window as it appears here - https://github.com/github/fetch/blob/master/fetch.js

  2. Just replace the fetch with some old http request option like

    XMLHttpRequest which for sure supported in serviceNow

https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest

Edit- Try to use it like this: xmlhttp

function sendRequest() {
  var xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
      console.log(this.responseText);
      return this.responseText;
    }
  };
  xhttp.open("GET", "https://dummyjson.com/products/1", true);
  xhttp.send();
} 

Based on your screenshot you are working with UI Builder, which seems to be restricted by ServiceNow. That's why you can't use fetch, I think you have to use the following to make HTTP Requests

helpers
.snHttp("/api/now/table/incident", {
  method: "POST",
  body: {
    description: "Sample description",
    close_notes: "Sample close notes",
    order: "-1"
  }
})
.then(({ response }) => {
  // handle POST request response
})
.catch(({ error }) => {
  // handle POST request errors
});

Link to ServiceNow Documentation - helpers.snHttp

Related