Reputation: 1444
I'm trying to send a POST request from an App Script application to a firebase cloud function. But I'm not being able to send correctly arrays inside this request. The request is sending the array in a messy way that the cloud function can't read it correctly
I'm using the following code:
const data = {
var1: 'string',
var2: {name: 'object'},
var3: new Date(),
var4: [1, 2, 3],
var5: [{name: 'any object'}, {name: 'inside an array'}],
}
const url = "https://us-central1-my-app.cloudfunctions.net/executeFunction";
const options = {
method: "post",
"Content-Type": "application/json", //I tried to change this content-type for other options
payload: data
};
const request = UrlFetchApp.fetch(url, options);
On the server side I tried to read the data using the following ways:
export const executeFunction = functions.https.onRequest(async(req, res) => {
//option 1
const data = JSON.parse(req.body);
res.send(JSON.stringify(data));
//option2
const data = req.body;
res.send(JSON.stringify(data);
})
But on the server the req.body
returns me the following value:
{
"var1":"string",
"var2":{"name":"object"},
"var3":"2020-07-14T18:45:21.946Z",
"var4":[Ljava.lang.Object;@5e1b03dd, // :(
"var5":[Ljava.lang.Object;@19d93f99 // :(
How can I get the array values correctly?
I suspect that it may be something related to the charset, but I already tried using "Content-Type": "application/json; charset=utf-8"
on the options
object and it didn't work.
Any ideas on how to solve it? :)
Update:
Thanks @Pickachu
I had to change 2 things: -stringify the payload -change the key on options from "Content-Type" to "contentType"
Here the code:
const options = {
method: "post",
contentType: "application/json", //changed here
payload: JSON.stringify(data) //and here
};
const request = UrlFetchApp.fetch(url, options);
Upvotes: 0
Views: 948
Reputation: 86
You are almost getting it. A POST request from UrlFetcgApp with a json payload should have the payload serialized:
https://developers.google.com/apps-script/reference/url-fetch/url-fetch-app#fetch(String,Object)
const options = {
...
payload: JSON.stringify(data)
};
And a firebase cloud function using a https trigger automatically parses the json body so there is no need to parse or stringify it.
export const executeFunction = functions.https.onRequest(async(req, res) => {
const data = req.body;
console.log(data.var1);
console.log(data.var2);
console.log(data.var3);
})
Upvotes: 4