我试图从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,服务器却给出了预期的结果。
问题解决了,首先是原因--node js服务器不接受任何请求体。虽然在postman中不需要改变任何默认设置,但在swift中似乎需要添加以下描述头的代码。
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")
当头值如上所示时,node js服务器就会正确接受请求体。