如何在Javascript中从POST请求中读取JSON值

时间:2018-01-10 20:44:37

标签: javascript ios json node.js swift

如何从客户端发送的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);
    }

   });

2 个答案:

答案 0 :(得分:0)

使用query

    var title = request.query.title;
    var body = request.query.body;
    var icon = request.query.photoUrl;

此外,请删除if (request.params)

待办事项

 if(title && body && icon){ 
     // do something
 }

答案 1 :(得分:0)

要使用request.query.myKey,请将URLQueryItem添加到客户端的网址,而不是将字典添加到urlRequest body

   var urlComponents: URLComponents {
            var components = URLComponents(string: urlString)!
            let tokenIdQueryItem = URLQueryItem(name: "TokenId", value: "tokenId-12345")
            let titleQueryItem = URLQueryItem(name: "title", value: "Congrats! You have a new follower.")
            let bodyQueryItem = URLQueryItem(name: "body", value: "John Doe is now following you")
            let photoUrlQueryItem  = URLQueryItem(name: "photoUrl", value: "photoUrl...")
            components.queryItems = [tokenIdQueryItem, titleQueryItem, bodyQueryItem, photoUrlQueryItem]
            return components
        }

   var request = URLRequest(url: urlComponents.url!)