0

Can somebody help me in sharing the example of implementing a post request. I have a web form and after filling all required parameters a json request should be created and it should be passed to the post API. I am using java script in Lit-html framework.

Thanks in Advance

Harry
  • 15
  • 2
  • 9
  • You might want to check out https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Using_XMLHttpRequest#Using_nothing_but_XMLHttpRequest, and this oldie-but-goodie: https://stackoverflow.com/questions/1973140/parsing-json-from-xmlhttprequest-responsejson – Cat Jul 29 '19 at 10:21

1 Answers1

0

here's a function i made for performing a JSON post and receiving a JSON response

async function jsonCall(url, payload) {

  const response = await fetch(url, {
    method: "POST",
    headers: {
      "Accept": "application/json",
      "Content-Type": "application/json",
    },
    body: JSON.stringify(payload)
  })

  return response.json()

}

you can use it like this:

async function main() {

  const result = await jsonCall("https://api.example.com/", {
    myData: 123,
    moreData: [1, 2, 3]
  })

  console.log("result!", result)

}
General Grievance
  • 4,555
  • 31
  • 31
  • 45
ChaseMoskal
  • 7,151
  • 5
  • 37
  • 50