How to post data URLSearchParams With Fetch in IE 11

2k Views Asked by At

When I am trying to post bodydata using URLSearchParams in fetch, its working in Chrome v72 and Edge v40 but not on IE11 (with polyfills).

On IE11: I am getting this error:

Error: unsupported BodyInit type

I am using the following polyfills for Edge/IE/etc browsers:

  • whatwg-fetch: "3.0.0" (A window.fetch polyfill)
  • url-search-params-polyfill: "5.0.0" (a simple polyfill for javascript URLSearchParams)

    const bodyData = new URLSearchParams() Object.keys(configJson).map(key => { bodyData.append(encodeURIComponent(key), encodeURIComponent(configJson[key])) })

    const opts = { method: 'POST', body: bodyData, headers: { 'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8' } }

    fetch(endPointUrl, opts)

1

There are 1 best solutions below

1
Sh4m On

You can use below

Example your request body

{..., body : objToBodyObj(obj) ..}

Below is function

function objToBodyObj(obj) {
  var str = "";
  for (var key in obj) {
    if (str != "") {
      str += "&";
    }
    str += key + "=" + encodeURIComponent(obj[key]);
  }
  return str;
}