Home > front end >  HTTP POST to Google Sheets (via Apps Script) not importing JSON body message contents?
HTTP POST to Google Sheets (via Apps Script) not importing JSON body message contents?

Time:09-19

I've designed a web app that posts order information to Google Sheets via HTTP POST and Google Apps Script. However, I am struggling to POST and extract the order information from the body JSON. I have tried 2 different methods and they both output the similar information but with the same data type - FileUpload. I've even attempted to import it as parameters as FormData() but repeatedly appending parameters didn't feel quite right.

Method 1

function method1() {
  var xml = new XMLHttpRequest();
  var data = JSON.stringify({ firstName: "Jay", lastName: "Smith" });
  xml.open("POST", url, true);
  /*   xml.setRequestHeader("Content-type", "application/json"); */
  xml.onreadystatechange = function () {
    if (xml.readyState === 4 && xml.status === 200) {
      alert(xml.responseText);
    }
  };
  xml.send(data);
}

Output

{postData=FileUpload, contextPath=, contentLength=38.0, parameters={}, parameter={}, queryString=}

Notice how the setRequestHeader() function is commented. No output would occur if it was uncommented making the content type set to JSON. Why will it not work?

Method 2

function method2() {
  const body = {
    firstName: "Jay",
    lastName: "Smith",
  };
  const options = {
    method: "POST",
    body: JSON.stringify(body),
  };

  fetch(url, options).then((res) => res.json());
}

Output

{contextPath=, parameters={}, parameter={}, queryString=, postData=FileUpload, contentLength=38.0}

Method 3 (Should I even consider this?)

function method3() {
  const formData = new FormData();
  formData.append("firstName", "Jay");
  formData.append("lastName", "Smith");
  fetch(url, {
    method: "POST",
    body: formData,
  }).then((res) => res.json());
}

Output

{contentLength=243.0, parameter={firstName=Jay, lastName=Smith}, queryString=, contextPath=, parameters={lastName=[Ljava.lang.Object;@6c4aece6, firstName=[Ljava.lang.Object;@3c461e46}}

The content length is considerably larger... this does not seem like an effective concept.


Google Apps Script doPost() Function

function doPost(e) {
  const sheet = SpreadsheetApp.openById(SHEETID).getSheetByName('Testing Inputs');
  sheet.getRange(3,1).setValue(e); // To display POST output
  const data = JSON.parse(request.postData.contents)
  sheet.getRange(5,1).setValue(data['firstName']) // Not writing "Jay"? 
  sheet.getRange(5,2).setValue(data['lastName']) // Not writing "Smith"?
}

In general, it appears data is coming through as body message content judging by the contentLength output but is it not JSON considering the postData is FileUpload? That may cause my Apps Script nor to be able to extract it right? Also, I thought I read that using fetch() is considerably better than using XMLHttpRequest() so should I be using my Method 2? Still not sure what am I doing wrong to populate it in individual cells in sheets using Apps Script?

Any help is appreciated!

Output Using sheet.getRange(3,1).setValue(JSON.stringify(e))

{"parameter":{},"postData":{"contents":"{\"firstName\":\"Jay\",\"lastName\":\"Smith\"}","length":38,"name":"postData","type":"text/plain"},"parameters":{},"contentLength":38,"queryString":"","contextPath":""}

CodePudding user response:

Based on the output provided by sheet.getRange(3,1).setValue(JSON.stringify(e)) (I'm not sure which of your methods generated this, but that method looks like it's the right one), your doPost as written should work, with one modification: I don't see a variable request defined, so I assume you intend request to be the http request object, which in an Apps Script web app is defined by the e parameter passed to the doPost (documentation). Therefore change this line

const data = JSON.parse(request.postData.contents)

to this one

const data = JSON.parse(e.postData.contents)
  • Related