简体   繁体   中英

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).

In javascript, I would do something like this

axios.post(url, {data:{"testConfigKey": "testing"}}

This is what I am doing in 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))

{ '{\n  "testConfigKey" : "testing"\n}': '' }

This is how my api endopint looks

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

let userConfig = req.body.testConfigKey;

It should give me "testing"

I basically refereed to this answer on 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()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM