BodyParser

public class BodyParser : RouterMiddleware

The BodyParser parses the body of the request prior to sending it to the handler. It reads the Content-Type of the message header and populates the RouterRequest body field with a corresponding ParsedBody enumeration.

In order for the BodyParser to be used it must first be registered with any routes that are interested in the ParsedBody payload.

ParsedBody enumeration:

The mappings from the incoming Content-Type to an internal representation of the body are as follows:

   .json([String: Any])          // "application/json"
   .text(String)                 // "text/*"
   .urlEncoded([String:String])  // "application/x-www-form-urlencoded"
   .multipart([Part])            // "multipart/form-data"
   .raw(Data)                    // Any other Content-Type

Each case has a corresponding convenience property, e.g. asURLEncoded: [String:String], for accessing the associated data.

Note: If you have not declared a Content-Type header, ParsedBody will be nil.

Usage Example:

In this example, all routes to the BodyParser middleware are registered to the BodyParser middleware. A request with “application/json”, ContentType header is received. It is then parsed as JSON and the value for “name” is returned in the response.

router.all("/name", middleware: BodyParser())
router.post("/name") { request, response, next in
    guard let jsonBody = request.parsedBody?.asJSON else {
        next()
        return
    }
    let name = jsonBody["name"] as? String ?? ""
    try response.send("Hello \(name)").end()
}

Note: When using Codable Routing in Kitura 2.x the BodyParser should not be registered to any codable routes (doing so will log the following error “No data in request. Codable routes do not allow the use of a BodyParser.” and the route handler will not be executed).

  • Initializes a BodyParser instance. Needed since default initalizer is internal.

    Usage Example:

     let middleware = BodyParser()
    

    Declaration

    Swift

    public init()
  • This function is called by the Kitura Router when an incoming request matches the route provided when the BodyParser was registered with the Router. It performs the parsing of the body content using parse(_:contentType). We don’t expect a user to call this function directly.

    Declaration

    Swift

    public func handle(request: RouterRequest, response: RouterResponse, next: @escaping () -> Void) throws

    Parameters

    request

    The RouterRequest object used to work with the incoming HTTP request.

    response

    The RouterResponse object used to respond to the HTTP request.

    next

    The closure called to invoke the next handler or middleware associated with the request.

  • This function is called by the Kitura Router when an incoming request matches the route provided when the BodyParser was registered with the Router. The middleware.handle(...) function will parse the body content of an incoming request using this function. A user can call this function directly but ordinarily won’t need to.

    Usage Example:

    In this example, the body of the request is parsed to be of the passed in contentType.

    request.body = BodyParser.parse(request, contentType: contentType)
    

    Declaration

    Swift

    public class func parse(_ message: RouterRequest, contentType: String?) -> ParsedBody?

    Parameters

    message

    Message coming from the socket.

    contentType

    The content type as a String.

    Return Value

    The parsed body.

  • Read the body data of the request.

    Usage Example:

    In this example, the body of the request is read into a constant (called bodyData) using an instance of RouterRequest (called request).

    let bodyData = try readBodyData(with: request)
    

    Throws

    Socket.Error if an error occurred while reading from a socket.

    Declaration

    Swift

    public class func readBodyData(with reader: RouterRequest) throws -> Data

    Parameters

    with

    The socket reader.

    Return Value

    The body data associated with the request.