通过ajax向firebase云消息发送帖子请求?

时间:2016-10-06 16:48:17

标签: javascript ajax firebase firebase-cloud-messaging

我正在尝试通过firebase向我的设备发送消息。但我得到了错误。我在预先的REST客户端上成功测试了它。这是来自其他客户端的消息

Content-Type: application/json
Authorization: key=MY-KEY
Content-Length: 106

POST /fcm/send HTTP/1.1
HOST: fcm.googleapis.com
content-type: application/json
authorization: key=MY-KEY
content-length: 106

{
  "to":"/topics/Self_Taught"
  "notification":
  {
    "body":"Hello"
  }
}    

基于此,我制作了我的javascript代码。不要担心砂砾,它是其他库,它可以正常工作。

$.ajax({
            url: "https://fcm.googleapis.com/fcm/send",
            type: "POST",
            contentType: "application/json",
            authorization: "key=MY-KEY",
            data: {
                "to": "/topics/Self_Taught",
                "notification": {
                    "body": message
                }

            },
            success: function (result) {
                $.gritter.add({
                    title: "",
                    text: result.message_id,
                    class_name: 'gritter-success'
                });
            },
            error: function (result) {
                $.gritter.add({
                    title: "",
                    text: result.error,
                    class_name: 'gritter-error'
                });
            }
        });

这就是我从result.error中得到的回复

function () { 
if (l) { 
    var t = l.length; 
    (function i(t) { 
        x.each(t, function (t, n) { 
        var r = x.type(n); 
        "function" === r ? e.unique && p.has(n) || l.push(n) : n && n.length && "string" !== r && i(n) 
        }) 
    })
    (arguments), n ? o = l.length : r && (s = t, c(r)) 
    }
    return this 
}

我按照此链接将“通知”更改为“数据”,将“正文”更改为“消息”。但我得到了同样的错误。 https://firebase.google.com/docs/cloud-messaging/android/topic-messaging#http_post_request

我的错误在哪里? :(谢谢你!

1 个答案:

答案 0 :(得分:3)

授权需要成为“标题”的一部分。通知数据需要作为字符串传递。试试下面:它有效:)

     $.ajax({        
            type : 'POST',
            url : "https://fcm.googleapis.com/fcm/send",
            headers : {
                Authorization : 'key=' + '<key>'
            },
            contentType : 'application/json',
            dataType: 'json',
            data: JSON.stringify({"to": "<instance ID>", "notification": {"title":"Test","body":"Test"}}),
            success : function(response) {
                console.log(response);
            },
            error : function(xhr, status, error) {
                console.log(xhr.error);                   
            }
        });