J
J
jjsds2020-05-07 00:34:32
Google Apps Script
jjsds, 2020-05-07 00:34:32

How to access the parameter in square brackets of a POST request?

I'm trying to write an application in Google app script that will receive post requests from the server and store their content in a table.

I am using doPost() method

My code is:

function doPost (e) {
  var tasklist = SpreadsheetApp.openByUrl(моя таблица);
  var tasks = tasklist.getSheetByName(мой лист);

  var dateTime = Utilities.formatDate(new Date(), "GMT+3", "dd.MM.yyy HH:mm:ss");
  var name = e.parameter.orderName;
  tasks.appendRow([dateTime, name]);
  return ContentService.createTextOutput("Успех");
}


The problem is that I can get the value of ordinary variables in the body of the post request, but there are no variables with the key[key2] format.

Here is an example of a POST request from the server:
orderName=zxx&payment[sys]=none&payment[systranid]=0&payment[orderid]=1705693330&payment[products][0][name]=Pencil+Glass&payment[products][0][quantity]=1&payment[products][0][amount ]=790&payment[products][0][price]=790&payment[amount]=790&formid=form189294992&formname=Cart

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexander Ivanov, 2020-05-07
@oshliaer

Note that the x-www-form-urlencoded. When you receive a form argument, you must "convert" it to the required format. In your case
const payments = JSON.parse(e.parameter.payments);
The following code returns the first element of the array

/**
 *
 * @param {GoogleAppsScript.Events.DoPost} e
 */
function doPost(e) {
  const payments = JSON.parse(e.parameter.payments);
  return ContentService.createTextOutput(JSON.stringify(payments.products[0]));
}

5eb3a269ca4ea797180580.png
If the query string is more interesting, then it's best to use the build for gas from https://github.com/sindresorhus/query-string .
A simpler representation can be taken here form2json.js
Accordingly, to get into doPostan object, you need to do an
form2Json(e.postData.contents)
example of my application
/* global form2Json */
/* exported doPost */
/**
 *
 * @param {GoogleAppsScript.Events.DoPost} e
 */
function doPost(e) {
  // const payments = JSON.parse(e.parameter.payments);
  return ContentService.createTextOutput(
    JSON.stringify(form2Json(e.postData.contents), null, '  ')
  );
}

5eb51b8925e51758421765.png
Note that it is not an array that is returned, but an object with indices. But that doesn't stop me from working.
const data = form2Json(contents);
console.log(JSON.stringify(data.payment.products[0]));

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question