0

The function below is contained in the Apps Script code.gs file:

function doPost(e) {
  if(typeof e !== 'undefined')
    return ContentService.createTextOutput(JSON.stringify(e.parameter));
}

If I make a request using fetch from the background.js of my Chrome extension and include the id parameter in the URL, I get the expected result.

const url = 'https://script.google.com/.../exec?id=123';

fetch(url)
  .then(response => response.text())
  .then(data => { console.log(data) }) // {"id":"123"}

Instead of writing id as a parameter in the URL, I would like to make the request using the POST method.

I tried to use the object below, but I don't know how to include the variable I want to send:

{
  method: 'POST',
  headers: {
    'Accept': 'application/json',
    'Content-Type': 'application/json'
  },
  body: {}
}
Andrew
  • 25
  • 1
  • 4
  • 1
    have you tried `body: { id: 123 }` ? And then seems that the data would be available as `JSON.parse(e.postData.contents)` in your function (see this prior question: https://stackoverflow.com/questions/12956354/how-to-access-body-of-post-request-in-app-script-using-dopostrequest) – erikor Jan 10 '23 at 02:56

2 Answers2

0

I believe your goal is as follows.

  • You want to send the value of id=123 with the request body instead of the query parameter.

In this case, how about the following modification?

Google Apps Script side:

function doPost(e) {
  if (typeof e !== 'undefined') {
    const value = JSON.parse(e.postData.contents); // This is the value from the request body.
    return ContentService.createTextOutput(JSON.stringify(value));
  }
}

Javascript side:

const url = "https://script.google.com/macros/s/###/exec";
const data = { id: 123 };
fetch(url, { method: "POST", body: JSON.stringify(data) })
  .then((res) => res.text())
  .then((res) => console.log(res));
  • By this modification, you can see the value of {"id":123} in the console.

Note:

References:

Tanaike
  • 181,128
  • 11
  • 97
  • 165
0

To include the data you want to send in the request body and to make a POST request using the fetch function, you can do the following:

const data = {id: '123'};

fetch(url, {
  method: 'POST',
  headers: {
    'Accept': 'application/json',
    'Content-Type': 'application/json'
  },
  body: JSON.stringify(data)
})
  .then(response => response.text())
  .then(data => { console.log(data) })

This send a POST request to the URL with data in the request body. The server-side function (in this case, doPost) will receive the data in the e.parameter object.

I hope this helps you.