@@ -57,47 +57,56 @@ router.post("/request", async (req: Request, res: Response) => {
5757 const { method, url, body, headers } = req . body ;
5858 let resBody ;
5959
60- if ( method && url ) {
61- try {
60+ if ( method && url ) {
61+ try {
6262 let safeHeaders : Record < string , string > = { } ;
6363 if ( headers && typeof headers === "object" && ! Array . isArray ( headers ) ) {
6464 for ( const [ key , value ] of Object . entries ( headers ) ) {
65- if (
66- typeof key === "string" &&
67- typeof value !== "undefined" &&
68- value !== null
69- ) {
65+ if ( typeof key === "string" && value != null ) {
7066 safeHeaders [ key ] = String ( value ) ;
7167 }
7268 }
7369 }
7470
71+ const outgoingBody =
72+ method === "GET"
73+ ? undefined
74+ : typeof body === "string"
75+ ? body
76+ : body !== undefined
77+ ? JSON . stringify ( body )
78+ : undefined ;
79+
80+ const hasContentType = Object . keys ( safeHeaders ) . some (
81+ ( h ) => h . toLowerCase ( ) === "content-type"
82+ ) ;
83+ if ( outgoingBody && ! hasContentType && typeof body !== "string" ) {
84+ safeHeaders [ "Content-Type" ] = "application/json" ;
85+ }
86+
7587 const response = await fetch ( url , {
7688 method : method ,
7789 headers : safeHeaders ,
78- body : method == "GET" ? undefined : JSON . stringify ( body )
90+ body : outgoingBody
7991 } ) ;
8092 const contenttype = await response . headers . get ( "content-type" ) ;
81- if ( contenttype ?. includes ( "application/json" ) ) {
82- resBody = await response . json ( )
83- }
84- else {
93+ if ( contenttype ?. includes ( "application/json" ) ) {
94+ resBody = await response . json ( ) ;
95+ } else {
8596 resBody = await response . text ( ) ;
8697 }
8798 res . json ( {
8899 status : response . status ,
89100 body : resBody ,
90101 headers : Object . fromEntries ( response . headers . entries ( ) )
91102 } ) ;
92- }
93- catch ( error ) {
103+ } catch ( error ) {
94104 res . status ( 400 ) . json ( {
95105 error : "There was an error while sending the request. Make sure that the url is well formatted"
96106 } ) ;
97107 console . error ( error ) ;
98108 }
99- }
100- else {
109+ } else {
101110 res . status ( 400 ) . json ( {
102111 error : "method and url are required in body"
103112 } ) ;
0 commit comments