send post request to firebase cloud messaging by a

2019-07-27 12:03发布

I'm trying to send a message to my device via firebase. But I got error. I tested it successfully on advance REST client. This is message from rest client

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"
  }
}    

Based on that, I made my javascript code. Don't worry about gritter, it's other library, and it works normally.

$.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'
                });
            }
        });

And this is what I get back from 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 
}

I followed this link by change "notification" to "data", and "body" to "message". But I got the same error. https://firebase.google.com/docs/cloud-messaging/android/topic-messaging#http_post_request

Where is my mistake? :( Thank you!

1条回答
Melony?
2楼-- · 2019-07-27 12:36

Authorization needs to be part of 'headers' & notification data needs to be passed as a string. Try Below: It works :)

     $.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);                   
            }
        });
查看更多
登录 后发表回答