0

I have a Google Cloud function written in Node-js that gets invoked each time somebody submits a Gupshup's serverless webview form

I expect to receive the following input in my web service:

{
    "linkId": "f42414e2-ce1a-4bf5-b40a-e88e4d4d9aee",
    "payload": [{
                  "fieldname": "name",
                  "fieldvalue": "Alice"
               },{
                   "fieldname": "gender",
                   "fieldvalue": "Male"
               },{
                   "fieldname": "account",
                   "fieldvalue": "savings"
               },{
                   "fieldname": "interest",
                   "fieldvalue": "Cooking"
               }],
    "time": 1479904354249,
    "userid": "UserID"
}

But i'm having trouble getting the objects inside "payload", time and userid objects.

This is my code:

exports.orderForm = (req, res) => {
  const data = req.body;
  const ref = data.userid;
  var propValue;

  console.log(req.method); // POST
  console.log(req.get('content-type')); // application/x-www-form-urlencoded
  console.log(req.body.linkid); // undefined
  console.log(req.body.payload[0].fieldname); // cannot read property from undefined error
  console.log(req.body.time); //undefined
  console.log(req.body.userid); // undefined

  // I attemp to print the properties, but they won't print
  for(var propName in req.body.payload) {
      propValue = req.body.payload[propName];
      console.log(propName, propValue);
  }

  console.log('JSON.stringify: ' + JSON.stringify(req.body)); // This prints the following:
  // JSON.stringify: {"{\"linkId\":\"f42414e2-ce1a-4bf5-b40a-e88e4d4d9aee\",\"payload\":":{"{\"fieldname\":\"account\",\"fieldvalue\":\"savings\"},{\"fieldname\":\"name\",\"fieldvalue\":\"Alice\"},{\"fieldname\":\"gender\",\"fieldvalue\":\"Male\"},{\"fieldname\":\"interest\",\"fieldvalue\":\"Cooking\"}":""}}

  res.sendStatus(200);
};

As you can see stringify allows to see all payload properties, but before that i cannot access them in the js object.

The second problem is that event after stringify i can't see time and userid.

What i suspect is i must handle requests of content-type="application/x-www-form-urlencoded" differently from what i'm used to, but i couldn't find any examples for that.

Shreyans
  • 1,738
  • 1
  • 13
  • 19
Ariel
  • 821
  • 2
  • 9
  • 19

1 Answers1

3

The response you receive from Gupshup to your callback after submission of the serverless webview form is already a stringified object.

Hence you need to parse it using JSON.parse() to get the JSON object and then you will be able to get the values.

Sample code

exports.orderForm = (req, res) => {
  const data = JSON.parse(req.body);
  console.log(data.linkid); // undefined
  console.log(data.payload[0].fieldname); 
  console.log(data.time); 
  console.log(data.userid);
};

This should resolve your issue.

Shreyans
  • 1,738
  • 1
  • 13
  • 19