How to forward multipart form request with node-fetch

693 Views Asked by At

I am trying to forward a graphql upload file through a node server. In my graphql resolver I have:

  async uploadFile ({ file }) {
   const { createReadStream, filename } = await file;
   const form = new FormData();
   const fileBuffer = Buffer.from(JSON.stringify(file), 'utf-8');
   
    form.append('file', fileBuffer, {
      contentType: 'multipart/form-data',
      filename: filename,
  });
  
   return fetch(`/someurl`, form)
    .then(handleSuccess)
    .catch(handleError)
  }

I simply want to forward the file without saving it to an upload directory. The error is 500, Internal Server Error. What am I doing wrong?

1

There are 1 best solutions below

0
On

I was able to make this work by changing the fetch request as follows:

const url = 'myurl'
const opts = {
      method: 'POST',
      body: form,
      headers: {...form.getHeaders()}
    }
    
 const response = await fetch(url, opts)
 const json = await response.json();