Fetch API and multer error while uploading file

后端 未结 2 1592
不知归路
不知归路 2021-01-02 02:35

I\'m trying to use fetch API to upload files to a node.js server (I\'m using github\'s pollyfill if it has something to do with it: https://github.com/github/fetch).

相关标签:
2条回答
  • 2021-01-02 03:18

    For those stumbling upon this post who have the error when using postman make sure to not specify the content-type in the headers.

    0 讨论(0)
  • 2021-01-02 03:18

    There is no need to assign a header {Content-Type': 'multipart/form-data'}: the browser substitutes its own.

    But if you expose it, then it is not specified boundary after content-type:multipart/form-data; boundary=... in Request Headers before Request Payload and that is causing the error on the server-side.

    If you open the browser console and see the headers, it will be seen.

    So, just:

    fetch(this.concatToUrl(url), {
      method: 'post',
      body: data,
    });
    

    Or, if you need custom headers you can add them like this:

    var headers = Object.assign({},
                                {'content-type': 'application/json'},
                                this.getHeaders(), 
                                {'Content-Type': 'multipart/form-data'}
    );
    
       // Removal should be case insensitive, or in any case, the header will be included:
    
    
    Object.keys(headers)
          .forEach( function(k) { 
             if (k.toLowerCase()==='content-type') delete headers[k] 
          })
    
    const data = new FormData();
    data.append('file', file);
    return fetch(this.concatToUrl(url), {
      method: 'post',
      headers: headers,
      body: data,
    });
    
    0 讨论(0)
提交回复
热议问题