迅捷结构作为请求主体

奥列格·萨维里耶夫(Oleg Savelyev)

尝试使用Vapor和Swift将数据发送到我的postgreSQL数据库中。

这是示例代码(Swift Struct作为请求正文)

struct ToDoResponseModel: Codable {
   var id: Int
   var Name: String
   var isComplete: Bool
}

let url = URL(string: "http://localhost:8080/todos")
guard let requestUrl = url else { fatalError() }
var request = URLRequest(url: requestUrl)
request.httpMethod = "POST"

// Set HTTP Request Header
request.setValue("application/json", forHTTPHeaderField: "Accept")
request.setValue("application/json", forHTTPHeaderField: "Content-Type")

let newTodoItem = ToDoResponseModel(id: 300, Name: "Urgent task 2", isComplete: true)

do {
    let jsonData = try JSONEncoder().encode(newTodoItem)
    request.httpBody = jsonData
}catch let jsonErr{
    print(jsonErr)
}

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

    if let error = error {
        print("Error took place \(error)")
        return
    }
    guard let data = data else {return}

    do {
        let todoItemModel = try JSONDecoder().decode(ToDoResponseModel.self, from: data)
        print("Response data:\n \(todoItemModel)")
        print("todoItemModel Name: \(todoItemModel.Name)")
        print("todoItemModel id: \(todoItemModel.id )")
    } catch let jsonErr {
        print(jsonErr)
    } 
}
task.resume()

但是我遇到了下一个错误:

keyNotFound(CodingKeys(stringValue:“ id”,intValue:nil),Swift.DecodingError.Context(codingPath:[],debugDescription:“没有与键CodingKeys相关联的值(stringValue:\” id \“,intValue:nil)(\ “ id \”)。“,underlyingError:nil))

错误已在此行修复:

let todoItemModel = try JSONDecoder().decode(ToDoResponseModel.self, from: data)

蒸气发送给我:

[错误] DecodingError.keyNotFound:密钥“ IsComplete”所需的值。(ErrorMiddleware.swift:26)

0xTim

看起来您是isComplete从客户端发送的,但是Vapor服务器正在等待IsComplete(大写字母I)

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章