从 GAS returns 错误写入 Firebase

Writing to Firebase from GAS returns error

我正在尝试从 Google Apps 脚本写入 Firebase。

我试试这个:

var act="https://SampleChat.firebaseIO-demo.com/users/fred/name.json";
UrlFetchApp.fetch(act,{"method":"post","payload":"test"});

我得到这个错误:

Request failed for https://SampleChat.firebaseIO-demo.com/users/fred/name.json
returned code 400. Truncated server response:
{ "error" : "Invalid data; couldn't parse JSON object, array, or value.
Perhaps you're using invalid characters in your key names." }...

问题

How do I write to Firebase from GAS? (What am I doing wrong?)

回答

You must stringify the payload object.

Here is a question and answer example.

我测试了一下,确实有效。


例子

function putToFire() {
  var payload = '{ "first": "Foo", "last": "Bar" }';
  var options = {
    "method": "put",
    "payload": payload
  };
  UrlFetchApp.fetch(
    "https://SampleChat.firebaseIO-demo.com/users/fred/name.json",             
     options
  );
}

关键技巧

Notice the single quotes ' around the payload object?

在下一行中:

  var payload = '{ "first": "Foo", "last": "Bar" }';

这种违反直觉的语法似乎是使这项工作成功的诀窍。 ;-)


可变负载的替代语法

如果你的payload是一个变量,你可以使用JSON.stringify():

  var payload=JSON.stringify({"first":"Foo","last":"Bar"});