File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change @@ -134,6 +134,23 @@ export async function readMultipartFormData(event: H3Event) {
134134 return parseMultipartData ( body , boundary ) ;
135135}
136136
137+ /**
138+ * Constructs a FormData object from an event.
139+ * @param event {H3Event}
140+ * @returns {FormData }
141+ *
142+ * ```ts
143+ * const eventHandler = event => {
144+ * const formData = await readFormData(event)
145+ * const email = formData.get("email")
146+ * const password = formData.get("password")
147+ * }
148+ * ```
149+ */
150+ export async function readFormData ( event : H3Event ) {
151+ return await event . request . formData ( ) ;
152+ }
153+
137154// --- Internal ---
138155
139156function _parseJSON ( body = "" , strict : boolean ) {
Original file line number Diff line number Diff line change @@ -11,6 +11,7 @@ import {
1111 getMethod ,
1212 getQuery ,
1313 getRequestURL ,
14+ readFormData ,
1415} from "../src" ;
1516
1617describe ( "" , ( ) => {
@@ -158,4 +159,28 @@ describe("", () => {
158159 expect ( ( await request . head ( "/post" ) ) . status ) . toBe ( 200 ) ;
159160 } ) ;
160161 } ) ;
162+
163+ const below18 = Number . parseInt ( process . version . slice ( 1 ) . split ( "." ) [ 0 ] ) < 18 ;
164+ describe . skipIf ( below18 ) ( "readFormData" , ( ) => {
165+ it ( "can handle form as FormData in event handler" , async ( ) => {
166+ app . use (
167+ "/" ,
168+ eventHandler ( async ( event ) => {
169+ const formData = await readFormData ( event ) ;
170+ const user = formData . get ( "user" ) ;
171+ expect ( formData instanceof FormData ) . toBe ( true ) ;
172+ expect ( user ) . toBe ( "john" ) ;
173+ return { user } ;
174+ } )
175+ ) ;
176+
177+ const result = await request
178+ . post ( "/api/test" )
179+ . set ( "content-type" , "application/x-www-form-urlencoded" )
180+ . field ( "user" , "john" ) ;
181+
182+ expect ( result . status ) . toBe ( 200 ) ;
183+ expect ( result . body ) . toMatchObject ( { user : "john" } ) ;
184+ } ) ;
185+ } ) ;
161186} ) ;
You can’t perform that action at this time.
0 commit comments