gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 11:52:28 25 4
gpt4 key购买 nike

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com