访问“请求”正文参数

Accessing `Request` body parameters

我正在尝试使用以下代码创建对第三方 API 的请求链:

import Vapor

final class APIController: RouteCollection {

    private let baseULR = "..."

    func boot(router: Router) throws {
        router.post("login", use: validate)
    }

    func validate(_ req: Request) throws -> Future<Response> {
        // Get the phone number of the user
        let phoneNumber = try req.content.syncGet(String.self, at: "phone_number")
        return try req.client().post("\(baseUrl)/...", beforeSend: { post in
            try post.content.encode(json: ["phone_number": phoneNumber])
        })
    }
}

但是在测试请求时,出现错误:

[ ERROR ] Abort.415: Unsupported Media Type (ContentCoders.swift:95)
[ DEBUG ] Suggested fixes for Abort.415: Register an `DataDecoder` using `ContentConfig`. Use one of the decoding methods that accepts a custom decoder. (ErrorMiddleware.swift:26)

不幸的是,我不知道如何解决。

您可以尝试提供 Content-Type 的有效载荷

func validate(_ req: Request) throws -> Future<Response> {
    // Get the phone number of the user
    return req.content.get(String.self, at: "phone_number").flatMap { phoneNumber in
        return try req.client().post("/...") {
            try [=10=].content.encode(["phone_number": phoneNumber], as: .json)
        }
    }
}

蒸汽 3:

将代码添加到 configure.swift 文件中的 public func configure(_ config: inout Config, _ env: inout Environment, _ services: inout Services) throws 函数

var contentConfig = ContentConfig()
//same to request content-type
contentConfig.use(decoder: URLEncodedFormDecoder(), for: .urlEncodedForm)
services.register(contentConfig)