【发布时间】:2018-07-10 01:17:01
【问题描述】:
我正在尝试为我的应用设置推送通知。我正在使用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!`
})
我得到带有令牌的数组并将其发送到 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 想要的数组(第一个代码-sn-p)? 或者你们还有其他想法我做错了什么吗? 提前谢谢大家!
【问题讨论】:
-
我也有同样的问题 -> @Zander 你是怎么解决这个问题的?
-
我现在无法访问工作代码,但我仍然记得这只是花括号的一个小问题。我发送了一个对象而不是一个数组(至少我猜是这样)。我认为将“body:JSON.stringify({tokenArray})”更改为“body:JSON.stringify(tokenArray)”为我解决了这个问题。
-
谢谢@Zander。当我使用 HTTP.post(流星服务器端而不是客户端获取:docs.meteor.com/api/http.html)时,我还发现了我这边的拼写错误,正文键被替换为«内容»或«数据»,在此之后就像一个魅力更正。
标签: javascript arrays json react-native expo