【发布时间】:2021-11-15 03:51:46
【问题描述】:
我正在尝试在 Swift 中提供我的 URL 发布请求正文。在 Swift 方面,一切似乎都运行良好,但我在 Node.js 中没有看到它。
创建 URL 的 Swift 函数:
func composeURL_Request(path: String, queryDict: [String:String], method: String? = nil, body: [String: Any]? = nil) -> URLRequest {
var components = URLComponents()
components.scheme = "http"
components.host = "localhost"
components.port = 4001
components.path = path
components.setQueryItems(with: queryDict)
var request = URLRequest(url: components.url!)
// optional components
if !(method == nil) {
request.httpMethod = method
}
if !(body == nil) {
do {
let jsonData = try JSONSerialization.data(withJSONObject: body!, options: .prettyPrinted)
request.httpBody = jsonData
} catch {
print(error.localizedDescription)
}
}
return request
}
此函数不会打印catch 中的任何内容,所以我认为它工作正常。
然后使用 Node.js,我能够打印出正确的查询参数,但打印出正文输出 {}。 Node.js 代码:
app.post("/host", (req, res) => {
const userID = req.query.userID;
const eventID = req.query.eventID;
const body = req.body;
console.log(userID)
console.log(eventID)
console.log(body)
})
编辑:
下面是调用 Swift 函数的代码:
let url = composeURL_Request(path: "/host",
queryDict: ["userID":
"erIIm5g5uQToAioCiKnOhP1griR2", "eventID": "eventID_001"],
method: "POST",
body: ["invited":
["Ax8Fx44T1sZAHUiTwyHRANqJOm43"],
"description": "long event
description. long event description. long event description",
"date": 1636943919175,
"includes image": false])
不幸的是,它看起来一团糟。
【问题讨论】:
-
什么是
jsonData打印?JSONSerialization显然没有失败,而是返回了一个空对象。 -
没有任何打印错误,但是打印成功的json序列化输出“204字节”