2017-07-06 29 views
0

我正在学习使用Node.js和multer上传文件。我配置了主要的app.js文件,以及upload.html。fetch()与FormData

我的形式:

<form id="uploadForm" action="/uploads" enctype="multipart/form-data" method="post"> 
    <input id="upload-input" type="file" name="uploads" multiple> 
    <button class="upload-button" type="button">File</button> 
</form> 

和的script.js与我试图处理表单数据,并取()张贴:

uploadInput.addEventListener('change', function() { 
    let files = event.target.files; 

    if(files.length > 0) { 
     let formData = new FormData(); 

     for(let i = 0; i < files.length; i++) { 
      let file = files[i]; 

      formData.append('uploads', file); 
     } 

     fetch('uploads', { 
      method: 'POST', 
      body: formData 
     }) 
     .then(res => res.json(), error => error.message); 
    } 
}); 

文件上传,一切都很好,除了两个错误。 首先显示在浏览器控制台:

uploader:1 Uncaught (in promise) SyntaxError: Unexpected token s in JSON at position 0 

其次在WebStorm IDE控制台:

(node:51729) [DEP0013] DeprecationWarning: Calling an asynchronous function without callback is deprecated. 

你有一个想法,为什么它有错误抛出,而一切工作正常?

回答

1

它看起来像这个问题是.then(res => res.json(), error => error.message);

的JSON解析错误,几乎可以肯定是因为你没有得到JSON回到你的回应。很难说出为什么你会得到弃用警告,但它可能与你的.then()电话有关。对于这两者,请执行一些有用的结果,例如console.log(res)console.log(error)

+0

你有一个想法如何处理这个JSON解析错误,如何省略它?不幸的日志响应和错误没有解决弃用警告的问题。 – veritimus

+0

如果不是JSON,则不能使用'json()'。如果这是成功的消息,你可能根本不需要做任何事情。 –

+0

我发送上传的表单数据文件,你建议什么,而不是json()? :) – veritimus