0

我想我在不理解的情况下从堆栈溢出中复制/粘贴代码出错了。

所以我想用正文快速创建一个发布请求。

正文包含键/值对(我是 swift 新手)。

在javascript中,我会做这样的事情

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

这就是我正在迅速做的事情

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"

我基本上参考了这个答案stackoverflowhttps ://stackoverflow.com/a/41082546/10433835

有人可以帮我弄清楚我做错了什么吗?

4

1 回答 1

1

请试试这个代码:

    // 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()
于 2020-02-06T10:26:23.250 回答