Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.4k views
in Technique[技术] by (71.8m points)

google apps script - How to use ContentService and doPost to create a REST API

I want to have the myFunction() send a payload which will be processed by the doPost and return some content based on the payload. I can only get these test scripts to work in either of these instances:

a) Use doGet(), not pass the payload but get the output returned as expected.

OR

b) Use doPost(), pass the payload but get an 405 code instead of the output.

What am I missing?

function doPost(e) {
  var ss = SpreadsheetApp.openById('<spreadsheet id for recording parameters>');
  var sheet = ss.getSheets()[0];
  var record;
  for (var i in e.parameters) {
    record = 'parameter: ' + i + ' = ' + e.parameters[i];
    sheet.getRange(sheet.getLastRow() + 1, 1, 1, 1).setValue(record);
  }
  var output = ContentService.createTextOutput();
  output.setContent("content to return");
  return output;
}

function myFunction() {
  var url = '<url of above script webapp, set to anonymous, anyone>';
  var payload = {payloadToSend : 'string to send'};
  var method = 'post'
  var response = UrlFetchApp.fetch(url, {method : method, payload: payload}).getContentText();
  Logger.log(response);
  return;
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The problem appears to be that the domain "script.googleusercontent.com", which is where ContentService content is served from, doesn't allow the POST method. When your doPost() handler returns the TextOuput it sends a redirect back to the client, which causes the client to send the POST again to script.googleusercontent.com, which is not allowed.

If you can use GET then that would be the recommended solution. If not, you may need to split the work into two parts: first POSTing with no response, then GETting to retrieve the response.

Update: As of Sept 21, 2012 this problem should now be fixed, and you can POST to the URL without any errors.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...