我有一个Rails应用程序,并且我想通过sidekiq发送一个发布请求到Expo,以便处理应用程序内通知。该应用程序的API是使用Node.JS构建的,并且推送令牌已使用以下代码成功执行:
axios({
method: "post",
url: "https://exp.host/--/api/v2/push/send",
data: {
to: result.expo_push_token,
title: `${data.user.first_name}`,
sound: "default",
body: shortMessage,
data: {
status: "ok",
body: shortMessage,
title: `${data.user.first_name}`,
msgUser: data.user,
convoId: data.room,
}
}
})
在Rails应用程序中,一切正常,直到我想将数据对象传递给应用程序。这是有效的方法:
push_tokens = PushToken.where(user_id: other_user)
push_tokens.each do |token|
params = ({
to: token.expo_push_token,
title: user.first_name,
sound: "default",
body: msg.body
})
puts params
puts params.class
x = Net::HTTP.post_form(URI.parse('https://exp.host/--/api/v2/push/send'), params)
puts x.body
然后,当我添加数据对象时,它给出了错误:{'errors':[{"code":'API_ERROR','message':'child \'data\' fails because [\'data\' must be an object], \'value\' must be an array.'}]}
push_tokens.each do |token|
params = ({
to: token.expo_push_token,
title: user.first_name,
sound: "default",
body: msg.body,
data: {
status: "ok",
msgUser: {
id: user.id,
avatar_file_name: user.avatar_file_name,
first_name: user.first_name,
},
convoId: msg.convo_id,
body: msg.body,
title: user.first_name,
},
})
puts params
puts params.class
x = Net::HTTP.post_form(URI.parse('https://exp.host/--/api/v2/push/send'), params)
puts x.body
最初,我正在将ActiveRecord传递给数据到msgUser: user
,并认为可能是问题所在,但是当我自己创建数组时msgUser: {id: user.id, avatar_file_name: user.avatar_file_name, first_name: user.first_name,},
并没有什么不同。简单的data: {status: 'ok'}
也不起作用。
我也尝试将data: [status: 'ok']
与[ ]
,params.to_json
和params.as_json
一起使用,但遇到同样的错误。
如何通过此Rails发布请求将这个data
对象成功发送到博览会推送令牌?
答案 0 :(得分:1)
这是我应用程序中的有效代码,您可以尝试一下
在您要触发作业的控制器中,执行以下操作
# Controller
push_tokens.each do |token|
WorkerClass.perform_async(token, @user)
end
# Worker file
class WorkerClass
def perform(token, user)
uri = URI.parse("https://exp.host/--/api/v2/push/send")
Net::HTTP.start(uri.host, uri.port, use_ssl: true) do |http|
http.verify_mode = OpenSSL::SSL::VERIFY_NONE
request = Net::HTTP::Post.new(uri.path, {'Content-Type' => 'application/json'})
request.body = {"to"=>token.expo_push_token, "title"=>user.first_name, "body"=>"your_message", "data"=>{"status"=>"ok"}}.to_json
response = http.request(request)
end
end
end