我正在尝试为我的应用程序设置推送通知。我正在使用Expo push-functionality
到目前为止,它运行得很好,但现在我想向多个人发送推送通知。在这种情况下,Expo 告诉我像这样发送 HTTP-Body:
[{
"to": "ExponentPushToken[xxxxxxxxxxxxxxxxxxxxxx]",
"sound": "default",
"body": "Hello world!"
}, {
"to": "ExponentPushToken[yyyyyyyyyyyyyyyyyyyyyy]",
"badge": 1,
"body": "You've got mail"
}]
我在这里有点挣扎。在我的应用程序中,我将其设置如下:
fetch('https://exp.host/--/api/v2/push/send', {
method: 'POST',
headers: {
Accept: 'application/json',
'Accept-encoding': 'gzip, deflate',
'Content-Type': 'application/json',
},
body: JSON.stringify({tokenArray})
});
tokenArray 来自 firebase 调用:
firebase.database().ref(`users/${user.uid}/`).once('value', snapshot => {
const token = snapshot.val().token;
tokenArray.push({
to: token,
title: 'Check out and Entvag!',
body: `Help ${creator} to decide!`
})
我获取带有 token 的数组并将其发送到 HTTP
这是我从服务器得到的响应(错误):
Response: Response {
"_bodyInit": "{\"errors\":[{\"code\":\"API_ERROR\",\"message\":\"child \\\"to\\\" fails because [\\\"to\\\" is required], \\\"value\\\" must be an array.\"}]}",
"_bodyText": "{\"errors\":[{\"code\":\"API_ERROR\",\"message\":\"child \\\"to\\\" fails because [\\\"to\\\" is required], \\\"value\\\" must be an array.\"}]}",
"headers": Headers {
"map": Object {
"cache-control": Array [
"public, max-age=0",
],
"content-length": Array [
"122",
],
"content-type": Array [
"application/json; charset=utf-8",
],
"date": Array [
"Wed, 31 Jan 2018 02:19:39 GMT",
],
"server": Array [
"nginx/1.11.3",
],
"strict-transport-security": Array [
"max-age=15724800; preload",
],
"vary": Array [
"Accept-Encoding, Origin",
],
"x-content-type-options": Array [
"nosniff",
],
},
},
"ok": false,
"status": 400,
"statusText": undefined,
"type": "default",
"url": "https://exp.host/--/api/v2/push/send",
}
我认为这与数组的构造方式有关(或者通过 JSON.stringify 构造???)在 console.log 上,数组(在 JSON.stringify 之后)如下所示:
{"tokenArray":[{"to":"ExponentPushToken[xxxxxxxxxxxxxxxxxxxxxx]","title":"Check out and Entvag!","body":"Help to decide: thisVal or thatVal}"}]}
如何构造一个看起来像 Expo 想要的数组(第一个代码片段)? 或者你们还有其他想法我做错了什么吗? 提前谢谢大家!
最佳答案
我很久以前就解决了这个错误,但忘记在 Stackoverflow 上更新它。 错误在这里:
fetch('https://exp.host/--/api/v2/push/send', {
method: 'POST',
headers: {
Accept: 'application/json',
'Accept-encoding': 'gzip, deflate',
'Content-Type': 'application/json',
},
body: JSON.stringify({tokenArray})
});
我使用 {} 包装 tokenArray 作为对象进行传递。这是工作代码片段:
fetch('https://exp.host/--/api/v2/push/send', {
method: 'POST',
headers: {
Accept: 'application/json',
'Accept-encoding': 'gzip, deflate',
'Content-Type': 'application/json',
},
body: JSON.stringify(tokenArray)
});
关于javascript - 在 React Native 上使用 Expo 发送多个推送通知,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48533532/