[英]How to send body in post request in swift
我想我在不理解的情況下從堆棧溢出復制/粘貼代碼時出錯了。
所以我想快速創建一個帶有正文的帖子請求。
正文包含鍵/值對(我是 swift 的新手)。
在javascript中,我會做這樣的事情
axios.post(url, {data:{"testConfigKey": "testing"}}
這就是我在 swift 中所做的
let url = URL(string: checkUserConfig)!
var request = URLRequest(url: url)
request.httpMethod = "POST"
let parameters = ["testConfigKey": "testing"] //not sure if this is correct
do {
request.httpBody = try JSONSerialization.data(withJSONObject: parameters, options: .prettyPrinted) // not sure if this is correct
} catch let error {
print(error.localizedDescription)
XCTFail("Unable to localize")
}
在我的后端,這在我的請求正文中給出以下響應 (console.log(req.body))
{ '{\n "testConfigKey" : "testing"\n}': '' }
這就是我的 api endopint 的樣子
app.post("/checkUserConfig", async (req, res) => {
console.log(req.body)
let userConfig = req.body.testConfigKey;
console.log(userConfig)
res.status(200).send(userConfig);
});
我想要的是當我在后端 api 中做這樣的事情時
let userConfig = req.body.testConfigKey;
它應該給我"testing"
我基本上參考了stackoverflow
上的這個答案: https : //stackoverflow.com/a/41082546/10433835
有人可以幫我弄清楚我做錯了什么嗎?
請試試這個代碼:
// prepare json data
let json: [String: Any] = ["testConfigKey": "testing"]
let parameters = try? JSONSerialization.data(withJSONObject: json)
// create post request
let url = URL(string: checkUserConfig)!
var apiRequest = URLRequest(url: url)
apiRequest.httpMethod = "POST"
apiRequest.addValue("application/json",forHTTPHeaderField: "Content-Type")
// insert json data to the request
apiRequest.httpBody = parameters
let task = URLSession.shared.dataTask(with: apiRequest) { data, response, error in
guard let data = data, error == nil else {
print(error?.localizedDescription ?? "No data Available")
return
}
let responseJSON = try? JSONSerialization.jsonObject(with: data, options: [])
if let responseJSON = responseJSON as? [String: Any] {
print(responseJSON)
}
}
task.resume()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.