Home > Software design >  `POST` request to script page
`POST` request to script page

Time:01-10

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: {}
}

CodePudding user response:

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:

CodePudding user response:

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.

  • Related