在Swift中发送json POST请求,读取json时返回错误。

问题描述 投票:0回答:1

我试图从Swift(5.1)客户端发送一个post请求,使用以下json作为请求体。

let json: [String: Any] = ["userName": "reef123",
                               "password": "abcd1234",
                               "wins": 100]

    let jsonData = try? JSONSerialization.data(withJSONObject: json, options: .prettyPrinted)
    let valid = JSONSerialization.isValidJSONObject(json);
    print(valid)
    // Set HTTP Request Body
    request.httpBody = jsonData


    // Perform HTTP Request
    let task = URLSession.shared.dataTask(with: request) { (data, response, error) in

            // Check for Error
            if let error = error {
                print("Error took place \(error)")
                return
            }

            let responseJSON = try? JSONSerialization.jsonObject(with: data!, options: [])
                if let responseJSON = responseJSON as? [String: Any] {
                    print(responseJSON)
                }
    }
    task.resume()

其中 "userName "是必填字段,我得到以下错误。

["message": User validation failed: userName: Path `userName` is required., "errors": {
    userName =     {
        kind = required;
        message = "Path `userName` is required.";
        name = ValidatorError;
        path = userName;
        properties =         {
            message = "Path `userName` is required.";
            path = userName;
            type = required;
        };
    };
}, "_message": User validation failed, "name": ValidationError]

从postman发送同样的json,服务器却给出了预期的结果。

json swift http post request
1个回答
0
投票

问题解决了,首先是原因--node js服务器不接受任何请求体。虽然在postman中不需要改变任何默认设置,但在swift中似乎需要添加以下描述头的代码。

request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")

当头值如上所示时,node js服务器就会正确接受请求体。

© www.soinside.com 2019 - 2024. All rights reserved.