简体   繁体   中英

Google Apps Script UrlFetchApp.fetch HTTP PUT Request to firebase not working

I'm trying to write data to a firebase database using Google Apps Script HTTP PUT Request. Here is what I have for code. I've debugged every line and everything works except for the actual PUT request.

Web page with one button in it.

<section>
    <input onclick="WriteInput()" type="button" value="Save Input">
</section>

<script>
 function onSuccess() {
  alert("on success ran");

};

function onFailure() {
  alert("on failure ran");

};

function WriteInput() {
  alert("it ran");
  google.script.run.withFailureHandler(onFailure)
    .withSuccessHandler(onSuccess)
    .putToFire();
}

</script>

This is the server side .gs code:

function doGet(){
  return HtmlService.createTemplateFromFile('WriteToFirebase')
        .evaluate() // evaluate MUST come before setting the NATIVE mode
        .setTitle('Test Write')
        .setSandboxMode(HtmlService.SandboxMode.NATIVE);
}

function putToFire() {

   var payload =
   {
     "first" : "Jack",
     "last" : "Sparrow"
   };

    var options =
    {
     "method" : "put",
     "payload" : payload
     };


    UrlFetchApp.fetch("https://SampleChat.firebaseIO-demo.com/users/fred/name.json", options );

    Logger.log(options);

   }

This is the Google documentation for issuing a HTTP request with Apps Script:

fetch url Google Documentation

This is the Firebase REST API documentation:

Firebase REST API

in cURL -X is to set the type of request. Eg PUT, POST, etc and -d is the indicate that data is to follow: The match up with Google Fetch is to set the params .

I must be just missing a syntax setting or something.

I actually found an answer to my problem. I can't remember what the error message was. I changed

THIS:

var options =
{
 "method" : "put",
 "payload" : payload
 };

TO THIS:

var options = {"method" : "put", "payload" : payload};

And it started working. I'm guessing that the multi-line code had end of line return characters in it, that Firebase would not parse. That's just my guess.

This example shows payload , options and the Apps Script UrlFetchApp.fetch service.

var payload = "{\"aa\" : \"" + UserID + "\", \"ab\" : \"" + Maker + "\", \"ac\" : " +
    AskingPrice + ", \"ad\" : \"" + Type +
    "\", \"ae\" : \"" + Description + "\", \"af\" : \"" + Function + "\", \"ag\" : \"" + 
    Cosmetic + "\", \"ah\" : \"" + dbID +
    "\", \"ai\" : \"" + IPaddr + "\"}";

var options = {"method" : "put", "payload" : payload};

UrlFetchApp.fetch("https://MyFireBaseDatabaseName.com/" + Ctgry + "/" 
+ dbID + "/.json", options );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM