【发布时间】:2018-06-20 02:46:29
【问题描述】:
如何从客户端发送的 POST 请求中读取值?我在 Swift 中从客户端发送POST 请求,如下所示:
let data = [ "tokenId": "tokenId-12345",
"title": "Congrats! You have a new follower.",
"body" : " John Doe is now following you.",
"photoUrl" : "url" ]
let body = try! JSONSerialization.data(withJSONObject: data, options: .sortedKeys)
request.httpBody = body
URLSession.shared.dataTask(with: request) { (data, response, error) in
// handle response.
}
在后端我需要从请求中获取值,所以我可以发送推送通知。
const functions = require('firebase-functions');
const admin = require('firebase-admin');
var serviceAccount = require("./service-account.json");
admin.initializeApp(functions.config().firebase);
exports.isMutual = functions.https.onRequest((request, response) => {
if (request.params) {
// get values. This doesn't work..
var title = request.params.title;
var body = request.params.body;
var icon = request.params.photoUrl;
const payload = {
notification: {
title:title,
body: body,
icon: icon
}
};
response.send(payload);
console.log(payload);
}
});
【问题讨论】:
-
var title = request.body.title;var body = request.body.body;var icon = request.body.photoUrl;更多信息:firebase.google.com/docs/functions/… -
@Peter 不工作。日志显示:
{ notification: { title: undefined, body: undefined, icon: undefined } }。这可能是什么原因? -
console.log与request.body是什么关系? -
日志显示:
{ '{"body":" John Doe is now following you.","photoUrl":"url","title":"Congrats! You have a new follower.","tokenId":"tokenId-12345"}': '' } -
哦,我看到整个帖子消息是对象的键。试试这个:
var body = JSON.parse(Object.keys(request.body)[0]); console.log(body)- 这是一个丑陋且快速的解决方案,不要在生产中使用它,只是尝试找出正文解析器出了什么问题)
标签: javascript ios json node.js swift