javascript - 如何从 Javascript 中的 POST 请求读取 JSON 值

标签 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);
    }

   });

最佳答案

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

   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!)

关于javascript - 如何从 Javascript 中的 POST 请求读取 JSON 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48195761/

相关文章:

iphone - 阅读推文中 HTML 链接的内容

java - 如何将 Json 转换为 POJO

javascript - 在浏览器打印上居中 Google map (V3)

javascript - 在数组中将 BlueBird promise 同步链接在一起

ios - 如何在Google Plus ios中获取共享的帖子ID?

ios - 如何使用 Parse 设置用户 'tagging'

java - 将 Realm 与 Gson 一起使用

javascript - JavaScript 中的字符串到日期转换

javascript - 如何将选定的 ng-options 选项的名称更改为自定义名称?

javascript - 响应式正方形网格内的响应式正方形网格