Search code examples
javascriptfetchmultipartform-dataform-data

fetch() with FormData


I am learning uploading files with Node.js and multer. I have configurated main app.js file, aswell as upload.html.

My form:

<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>

and script.js with which I am trying to handle form data and posting it with fetch():

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);
    }
});

Files are uploading and everything is fine except two errors. First displays at browser console:

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

And second in WebStorm IDE console:

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

Do you have an idea why it's throwing with errors, while everything works fine?


Solution

  • It looks like the problem is with .then(res => res.json(), error => error.message);

    The JSON parsing error is almost certainly because you're not getting JSON back in your response. It's hard to tell why exactly you're getting the deprecation warning, but it may be related to your .then() call. For both, do something useful with the result, such as console.log(res) and console.log(error).