Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

416
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda