How to do relevant operations before the fetch request is successful

  var fetchData = async (url, method, data) => {
      var options;
      var dataStr = "";
      var headers = {
        "Accept": "application/json",
        "Content-Type": "application/x-www-form-urlencoded"
      };
      // get 
      if (method === "get") {
        if (typeof data === "object") {
          Object.keys(data).forEach(key => {
            dataStr += `${key}=${data[key]}&`
          });
          if (dataStr) {
            dataStr = dataStr.substring(0, dataStr.length - 1)
          };
          url = `${url}?${dataStr}`;
        }
        options = {
          method: "GET",
          headers,
        }
      } else {
        var formData = new FormData();
        for (var key in data) {
          formData.append(key, data[key])
        }
        options = {
          method: "POST",
          body: formData
        }
      }
      var response = await fetch(url, options);
      var res = await response.json();
      return res;
}

this is an encapsulated fetch request. How to use fetch request to implement ajax beforesend before the request succeeds, for example, add a loading... prompt

May.16,2022

just add beforesend before await fetch () .

Menu