如何用Vapor获取JSON并在Leaf模板展示?报错求助
解决Vapor请求外部JSON时的"Unsupported Media Type"错误
你遇到的"Unsupported Media Type"错误,核心原因是Vapor的Content解码机制无法识别响应的Content-Type。S3存储的JSON文件默认可能返回text/plain而非标准的application/json,导致解码流程失败。
方案1:强制指定JSON解码格式
在解码时手动指定使用JSON解码器,忽略响应头的Content-Type限制:
修改indexHandler中的解码逻辑:
let json = try res.content.decode([Listing].self, using: .json)
同时优化错误处理,打印具体错误信息以便排查:
catch { print("解码失败:\(error)") return req.eventLoop.makeFailedFuture(error) }
方案2:修正S3文件的Content-Type
登录AWS S3控制台,找到目标JSON文件,修改其元数据,将Content-Type设置为application/json。这是更合规的长期解决方案,确保后续所有请求都能被正确识别。
修改后的完整indexHandler示例
func indexHandler(_ req: Request) -> EventLoopFuture<View> { return req.client.get("https://streeteasydaily.s3.us-west-2.amazonaws.com/streeteasy1.json").flatMap { res in do { // 强制按JSON格式解码 let json = try res.content.decode([Listing].self, using: .json) print(json[0].photos[0]) let context = IndexContext(title: "Homepage", listings: json) return try req.view.render("index", context) } catch { // 打印具体错误信息 print("解码失败:\(error)") return req.eventLoop.makeFailedFuture(error) } } }
内容的提问来源于stack exchange,提问作者Nat Serrano
相关产品推荐
相关产品推荐

