Home > Software design >  How to create javascript Request Object with Body type as form-data file
How to create javascript Request Object with Body type as form-data file

Time:06-27

enter image description here


I am trying to code POST REST API request as shown in the above Postman screenshot.

Here is my code:

import { fromFetch } from 'rxjs/fetch';
import { switchMap } from 'rxjs/operators';

interface FetchRequest<TBody> {
  method?: FetchMethod;
  body?: TBody;
  headers?: FetchHeaders;
  isBlobRequest?: boolean;
}

export const request = <TBody extends BodyInit = BodyInit>(
  url: string,
  fetchRequest?: FetchRequest<TBody>,
  contentType: string
) => {
  const { method = 'POST', body, headers } = fetchRequest ?? {};
  const { dispatch } = createStore();
  let request = new Request(`${domainUrl}${url}`, {
    method,
    body: body ? body : null,
    headers: {
      ...headers,
      'Content-type': contentType ,
    },
    credentials: 'include',
  });
  
  return fromFetch(request).pipe(
    switchMap((response: Response) => {
      if (response.status === SUCCESS_CODE) {
        if (isBlobRequest) {
          return response.blob();
        }
        return response.text();
      } else if (response.status === USER_SESSION_EXPIRED_CODE) {
        dispatch(authAsyncActions.setSessionExpired());
        throw response;
      } else {
        // This triggers error-handling and allows us to inspect the entire
        // error response including its status and body
        throw response;
      }
    })
  );
};


const callUploadAPI = (file) => {

      let formData = new FormData();
      formData.append('file', file);
      request(`urlUploadFile`, { method: 'POST', body: formData}, 'application/vnd.ms-excel')

}


In above code I am using fromFetch of "rxjs/fetch" to call the POST REST API and passing "Request" object in fromFetch().

Request interface is inside typescript as per the below screenshot.

enter image description here


Backend is Python flask server and on the backend side in Python code I am using

file = request.files['file']

to get the file which is working when I call the API through Postman but when I call the API through frontend code it is not getting file.

How can I set the Request "Body" type as "form-data" and "KEY" type as File in frontend code?

CodePudding user response:

You're explicitly setting the Content-type to application/vnd.ms-excel, but you don't need to set this header

As far as I know, if the body of a fetch request is a FormData object, the browser automatically sets the content type header to multipart/form-data

  • Related