Search code examples
node.jsexpressmultipartform-datansfetchrequestform-data

invalid json response body error with Express node-fetch using formData


I'm trying to do http request from nodeJS, this is the following request:

    const form = new FormData();
    form.append('text 1', 'sometext');
    form.append('file', fs.createReadStream("foo.txt"));
    fetch('url', {
            method: 'POST',
            headers: {
                'Content-Type': 'multipart/form-data'
            },
            body: form,
        })
        .then(res => res.json())
        .then(json => {
            console.log('res', json);
        }).catch(err => {
            console.error(err);
            return ReE(res, err.message, 500);
        });

})

But I'm getting the the following error

"error": "invalid json response body at reason: Unexpected token < in JSON at position 0"

What Am I doing wrong?


Solution

  • Try res => console.log(res) in your first .then() block to see what the response is. Usually that error "Unexpected token < in JSON..." means that the response returned some html and the "<" in the error is an opening tag.