Home > Back-end >  Post request failed with error code 400 when submitting Google form
Post request failed with error code 400 when submitting Google form

Time:08-19

I am trying to automate data entry in Google forms and following is my code but I am getting

Exception: Request failed for https://docs.google.com returned code 400. Truncated server:...

function myFunction() {
  var formUrl = "https://docs.google.com/forms/u/0/d/e/1FAIpQLScbvM7LZJEL-Cv-Bc1mg1Tid_R2QujW0N4Z4ytfsnztpz9_1A/formResponse";
  const ss = SpreadsheetApp.getActive();
  var sh = ss.getSheetByName("Sheet1");
  const vs = sh.getRange(1, 1, sh.getLastRow(), sh.getLastColumn()).getValues();
  vs.forEach(r => {
    var datamap = {
      "entry.1870580307": r[0],
      "emailAddress": r[1],
      "entry.172794055": r[2],
      "entry.2041507911": r[3],
      "entry.981764969": r[4],
      "entry.1599200340": r[5],
      "entry.835533968": r[6],
      "entry.652935633": r[7]
    };
    var options = {
      "method": "post",
      "payload": datamap
    };
    UrlFetchApp.fetch(formUrl, options);
  });
}

Link to my spreadsheet ,
Google Form link

CodePudding user response:

Edit: Thanks to @TheMaster's comments we found another roadblock. It seems that you won't be able to easily automate posting to this form unless you have some say on what settings it should have.

The sample form that you shared has enabled the option to "Send responders a copy of their response". This triggers a CAPTCHA to prevent abuse and the form requires a g-recaptcha-response in the POST parameters. I wouldn't go as far as to say that reCAPTCHA is unbeatable but it's not feasible for us to even consider bypassing it. As long as the captcha is in place you won't be able to post to the form with a script.

I made a copy of your form without the setting to send a copy of the responses and this did not ask for a captcha. In that case your script did work, but keep in mind that there are field validations. Your original script was including the header row from the spreadsheet, which did not pass the email validation and can also return a 400 error. You can correct by modifying your range like this:

  const vs = sh.getRange(2, 1, sh.getLastRow()-1, sh.getLastColumn()).getValues();

Alternatively, you can just keep the range as it is and use shift() to remove the first element in the array.

  const vs = sh.getRange(1, 1, sh.getLastRow(), sh.getLastColumn()).getValues();
  vs.shift()

Still, keep in mind that this will only work for captcha-less Forms. There may be other triggers that enforce captcha so you will probably only be able to automate posting to specific Forms or ones that you have some control over.

  • Related