File tree Expand file tree Collapse file tree 2 files changed +27
-9
lines changed
Expand file tree Collapse file tree 2 files changed +27
-9
lines changed Original file line number Diff line number Diff line change @@ -25,16 +25,15 @@ export function readRawBody<E extends Encoding = "utf8">(
2525 // Ensure using correct HTTP method before attempt to read payload
2626 assertMethod ( event , PayloadMethods ) ;
2727
28- if ( RawBodySymbol in event . node . req ) {
29- const promise = Promise . resolve ( ( event . node . req as any ) [ RawBodySymbol ] ) ;
28+ // Reuse body if already read
29+ const _rawBody =
30+ ( event . node . req as any ) [ RawBodySymbol ] ||
31+ ( event . node . req as any ) . body ; /* unjs/unenv #8 */
32+ if ( _rawBody ) {
33+ const promise = Promise . resolve ( _rawBody ) ;
3034 return encoding ? promise . then ( ( buff ) => buff . toString ( encoding ) ) : promise ;
3135 }
3236
33- // Workaround for unenv issue https://github.com/unjs/unenv/issues/8
34- if ( "body" in event . node . req ) {
35- return Promise . resolve ( ( event . node . req as any ) . body ) ;
36- }
37-
3837 if ( ! Number . parseInt ( event . node . req . headers [ "content-length" ] || "" ) ) {
3938 return Promise . resolve ( undefined ) ;
4039 }
@@ -79,8 +78,7 @@ export async function readBody<T = any>(event: H3Event): Promise<T> {
7978 return ( event . node . req as any ) [ ParsedBodySymbol ] ;
8079 }
8180
82- // TODO: Handle buffer
83- const body = ( await readRawBody ( event ) ) as string ;
81+ const body = await readRawBody ( event , "utf8" ) ;
8482
8583 if (
8684 event . node . req . headers [ "content-type" ] ===
Original file line number Diff line number Diff line change @@ -174,6 +174,26 @@ describe("", () => {
174174 expect ( result . text ) . toBe ( "200" ) ;
175175 } ) ;
176176
177+ it ( "handle raw body with buffer type (unenv)" , async ( ) => {
178+ app . use (
179+ "/" ,
180+ eventHandler ( async ( event ) => {
181+ // Emulate unenv
182+ // @ts -ignore
183+ event . node . req . body = Buffer . from ( "test" ) ;
184+
185+ const body = await readBody ( event ) ;
186+ expect ( body ) . toMatchObject ( "test" ) ;
187+
188+ return "200" ;
189+ } )
190+ ) ;
191+
192+ const result = await request . post ( "/api/test" ) . send ( ) ;
193+
194+ expect ( result . text ) . toBe ( "200" ) ;
195+ } ) ;
196+
177197 it ( "parses multipart form data" , async ( ) => {
178198 app . use (
179199 "/" ,
You can’t perform that action at this time.
0 commit comments