簡體   English   中英

如何從JavaScript中的POST請求讀取JSON值

[英]How to read JSON values from POST Request in Javascript

如何從客戶端發送的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);
    }

   });

使用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
 }

要使用request.query.myKey ,請將URLQueryItem添加到客戶端的url中,而不是將字典添加到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!)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM