[英]How to send body in post request in swift
I think I went somewhere wrong copying/pasting code from stack overflow without understanding.我想我在不理解的情况下从堆栈溢出复制/粘贴代码时出错了。
So I want to create a post request in swift with a body.所以我想快速创建一个带有正文的帖子请求。
The body contains key/value pair (I am new to swift).正文包含键/值对(我是 swift 的新手)。
In javascript, I would do something like this在javascript中,我会做这样的事情
axios.post(url, {data:{"testConfigKey": "testing"}}
This is what I am doing in swift这就是我在 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")
}
In my backend this is giving following response in my request body (console.log(req.body))在我的后端,这在我的请求正文中给出以下响应 (console.log(req.body))
{ '{\n "testConfigKey" : "testing"\n}': '' }
This is how my api endopint looks这就是我的 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);
});
What I want is when I do something like this in my backend api我想要的是当我在后端 api 中做这样的事情时
let userConfig = req.body.testConfigKey;
It should give me "testing"
它应该给我
"testing"
I basically refereed to this answer on stackoverflow
: https://stackoverflow.com/a/41082546/10433835我基本上参考了
stackoverflow
上的这个答案: https : //stackoverflow.com/a/41082546/10433835
Can someone help me in figuring out what I am doing wrong?有人可以帮我弄清楚我做错了什么吗?
Please Try this code :请试试这个代码:
// 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.