title: How to POST with multipart/form-data header and FormData using fetch
body: <p>This is a CURL example which works fine:</p>
  
  <pre><code>curl -X POST \
    &lt;url&gt; \
    -H 'authorization: Bearer &lt;token&gt;' \
    -H 'content-type: multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW' \
    -F file=@algorithm.jpg \
    -F userId=&lt;userId&gt;
  </code></pre>
  
  <p>I'm trying to reproduce this request using <a href="https://github.com/matthew-andrews/isomorphic-fetch" rel="noreferrer">isomorphic-fetch</a>.</p>
  
  <p>I've tried the following code:</p>
  
  <pre><code>const formData = new FormData();
  formData.append('file', file);
  formData.append('userId', userId);
  
  return fetch(`&lt;url&gt;`, {      
    method: 'POST',
    headers: {
      'Content-Length': file.length
      'Authorization: Bearer &lt;authorization token&gt;',
      'Content-Type': 'multipart/form-data'
    },
    body: formData
  })`
  </code></pre>
  
  <p>I use <code>fs.readFileSync</code> in order to generate the <code>file</code> passed to <code>FormData</code>.</p>
  
  <p>The previous example returns a <code>401</code> HTTP status code (unauthorized) with an error message saying that the <code>userId</code> embedded in the token (sent via header) does not match the <code>userId</code> passed from <code>formData</code>.</p>
  
  <p>So my suspicion is that the <code>FormData</code> that arrives to the REST API is not adequately formed.</p>
  
  <p>The problem may be related with the <code>Content-Length</code> header, but I didn't find a better way to calculate it (if I don't use the <code>Content-Length</code> header I get a <code>411</code> HTTP status code <code>Content-Length</code> header missing).</p>
  
  <p>Could be the case that this is failing because of an incorrect value in the <code>Content-Length</code> header?</p>
  
  <p>Any other suggestions on why this is failing or how to better debug it?</p>
  
  <p>If further info is needed to clarify this problem, please just ask.</p>
  
  <p><strong>UPDATE</strong></p>
  
  <p>I've tried the <a href="https://github.com/form-data/form-data" rel="noreferrer">form-data</a> module in order to get the right <code>Content-Length</code> value using the method <code>formData.getLengthSync()</code></p>
  
  <p>However the problem remains the same (<code>401</code> error HTTP status code response).</p>