2017-07-06 26 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