从GAS写入Firebase会返回错误

时间:2015-08-14 07:15:17

标签: google-apps-script firebase urlfetch

我正在尝试从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." }...

问题

  

如何从GAS写入Firebase?(我做错了什么?)

1 个答案:

答案 0 :(得分:2)

答案

  

您必须stringify payload个对象。

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
  );
}

关键技巧

  

请注意'对象周围的单引号payload

在以下行中:

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

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

可变有效负载的替代语法

如果您的payload是变量,则可以使用JSON.stringify()

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