Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

423
Vistas
How to create javascript Request Object with Body type as form-data file

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?

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

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

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda