Accessing `Request` body parameters

Viewed 838

I'm trying to create a chain of requests to third-party API with the following code:

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])
        })
    }
}

But when testing request, I'm getting an error:

[ 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)

That, unfortunately, I don't understand how to fix.

2 Answers

You could try to provide a Content-Type of a payload

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 $0.content.encode(["phone_number": phoneNumber], as: .json)
        }
    }
}

Vapor 3:

add code to public func configure(_ config: inout Config, _ env: inout Environment, _ services: inout Services) throws function in configure.swift file

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