英文:
Backend project on swift 5.8 and vapor
问题
我正在参加一个蒸汽视频课程。我严格按照它的要求编写代码,但当我尝试发送一个 Post 请求(通过 Postman)时,得到一个自定义错误代码。在课程中一切正常,看起来代码是一样的。有人知道该怎么办吗?
import Foundation
import Fluent
import Vapor
struct ProductsController: RouteCollection {
func boot(routes: Vapor.RoutesBuilder) throws {
let productsGroup = routes.grouped("products")
productsGroup.post(use: createHandler)
productsGroup.get(use: getAllHandler)
}
func createHandler(_ req: Request) async throws -> Product {
guard let product = try? req.content.decode(Product.self) else {
throw Abort(.custom(code: 499, reasonPhrase: "无法解码产品模型的内容"))
}
try await product.save(on: req.db)
return product
}
func getAllHandler(_ req: Request) async throws -> [Product] {
let products = try await Product.query(on: req.db).all()
return products
}
}
在 routes.swift
文件中有一个连接:
import Fluent
import Vapor
func routes(_ app: Application) throws {
try app.register(collection: ProductsController())
}
这是来自视频课程的代码。
英文:
I'm taking a vapor video course. I write code strictly according to it, and when I try to send a Post request (by postman), get a custom error code. In the course, everything is fine and it seems that the code is identical. Does anyone know what to do ?
import Foundation
import Fluent
import Vapor
struct ProductsController: RouteCollection {
func boot(routes: Vapor.RoutesBuilder) throws {
let productsGroup = routes.grouped("products")
productsGroup.post(use: createHandler)
productsGroup.get(use: getAllHandler)
}
func createHandler(_ req: Request) async throws -> Product {
guard let product = try? req.content.decode(Product.self) else {
throw Abort(.custom(code: 499, reasonPhrase: "Не получилось декодировать контент в модель продукта"))
}
try await product.save(on: req.db)
return product
}
func getAllHandler(_ req: Request) async throws -> [Product] {
let products = try await Product.query(on: req.db).all()
return products
}
}
There is a connection in the routes.swift file.
import Fluent
import Vapor
func routes(_ app: Application) throws {
try app.register(collection: ProductsController())
}
And here is the
code from the video course
答案1
得分: 1
几乎可以确定你的解码出现问题是由于产品结构字段与HTML表单字段之间的以下一个或多个差异导致的。请检查以下内容:
- 每个Product字段都存在HTML名称标签。
- 如果表单输入可以为空,那么结构字段定义是可选的。
- 表单输入类型是否合适。例如,解码日期和整数可能更容易将它们作为字符串解码,然后进行后处理。
你可以通过注释掉结构字段并检查空结构的解码来找出哪些字段出现了问题。然后逐一取消注释,直到再次出现错误。
英文:
It is almost certain your decode is failing due to one or more of the following differences between your Product structure fields and the HTML form’s fields. Check:
- HTML name tags exist for every field in Product.
- If a form input may be null then the struct field definition is optional.
- The form input type is appropriate. For example, decoding dates and integers may be easier done as strings and then post-process.
You can work out which ones are failing by commenting out the struct fields and checking an empty struct decodes. Then uncomment one-by-one until you hit the error again.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论