通过ajax将发布请求发送到Firebase云消息传递? [英] send post request to firebase cloud messaging by ajax?
问题描述
我正在尝试通过Firebase向我的设备发送消息.但是我出错了.我已经在高级REST客户端上成功测试了它.这是来自其他客户的消息
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"
}
}
基于此,我编写了JavaScript代码.不用担心gritter,它是另一个库,它可以正常工作.
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'
});
}
});
这就是我从result.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
}
在此链接之后,我将通知"更改为数据",将正文"更改为消息".但是我遇到了同样的错误. https://firebase.google.com/docs/cloud-messaging /android/topic-messaging#http_post_request
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!
推荐答案
授权必须是标头"和&通知数据需要作为字符串传递.尝试以下:有效:)
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);
}
});
这篇关于通过ajax将发布请求发送到Firebase云消息传递?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!