Laurent Ades
Laurent Ades

Reputation: 23

Sending form-data / application/x-www-form-urlencoded body for OpenWhisk/Kitura Swift HTTP POST Request

I am working my way through using IBM Cloud Bluemix environment with their Kitura flavor of server side Swift implementation. Of course, key to this is the ability to make all sorts of HTTP requests So far I have been able to handle GET requests and POST requests with pure JSON body. I am stuck when it comes to form-data or application/x-www-form-urlencoded. From what I read, it appears that I should be using the Kitura-provided BodyParser class, but I'm afraid I am not even sure how to actually use it in code. I have mostly used the following very useful posts to make my way so far. From Rob Allen From Horea Porutiu From Kevin Hoyt

As far as i understand it now I will need to use the BodyParser and Router classes from Kitura, but it seems to me that htose are arlredy taken care of in IBM Cloud Function implementation of OpenWhisk + Kitura Swift... so I am not too sure now...

Any idea or pointer anyone ? Thanks

Upvotes: 0

Views: 988

Answers (2)

Rob Allen
Rob Allen

Reputation: 12778

You can use request.readString() to read the body information in its raw format.

If you have the BodyParser middleware in play using:

router.all("/name", middleware: BodyParser())

Then you can use this for urlencoded bodies:

router.post("/name") { request, response, next in
    guard let parsedBody = request.body else {
        next()
        return
    }

    switch parsedBody {
        case .urlEncoded(let data):
            let name = data["name"].string ?? ""
            try response.send("Hello \(name)").end()
        default:
            break
    }
    next()
}

Where data is a [String:String] dictionary.

Upvotes: 2

Laurent Ades
Laurent Ades

Reputation: 23

ok, i answered my own question with further understanding that Kitura and Kitura-Net are 2 different things. The ClientRequest Class in Kitura-Net handles all this. All here

Upvotes: 1

Related Questions