Handling POST using Warp/WAI
Asked Answered
O

2

8

How do you retrieve data from a POST request using Network.Wai and Warp?

Say for example, I have a simple webpage

....
<form method="POST" action="/handlepost">
    <input name="name" type="text" />
    <input type="submit" />
</form>
....

When the user clicks submit, how can I retrieve this data? I know how to get GET data (queryString)

for example

app :: Application
app request = case rawPathInfo request of
                   "/" -> return $ displayForm
                   "/handlePost" -> return $ handlepost
                   _ -> return $ notFound

displayForm :: Response
displayForm = ResponseBuilder
    status200
    [("Content-Type", "text/html")] $
    fromByteString "<form method='POST' action='/handlepost'><input name="name" type="text" /><input type='submit'></form>"

handlePost :: Request -> Response
handlePost req = undefined -- how do I examine the contents of POST?
Otorhinolaryngology answered 14/9, 2011 at 21:0 Comment(0)
D
11

Just to add to hammar's answer: the wai package itself just defines the interface, it doesn't provide any helper functions. What you're looking for is the wai-extra package, in particular parseRequestBody. Note that this allows you to control exactly how the uploaded files are stored, such as in temporary files or in memory.

Dagon answered 15/9, 2011 at 2:20 Comment(1)
Also langnostic.blogspot.de/2013/04/… provides a great example on how parseRequestBody can be used. The wai-extra documentation is a little cumbersome when it comes to setting the argument of type Sink x y right.Kinsman
S
8

WAI is quite a low level interface, so POST data is left unprocessed in the request body, just as it was received. You should be able to grab it using the requestBody function.

Of course, you will then have to parse it, as it's typically encoded in the application/x-www-form-urlencoded format (or multipart/form-data for a form with file upload). I suspect there might be helper functions for this somewhere, but I could not find any in the WAI package itself, at least.

Sheehan answered 14/9, 2011 at 21:22 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.