Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 882
User100696 Avatar asked May 17 '19 01:05

User100696


2 Answers

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.

like image 158
joshuamango Avatar answered Oct 15 '22 14:10

joshuamango


The body is consumed after calling .json(), not sure you can access it afterwards. A simple workaround: get the raw body and parse it yourself:

async function safeParseJSON(response) {
    const body = await response.text();
    try {
        return JSON.parse(body);
    } catch (err) {
        console.error("Error:", err);
        console.error("Response body:", body);
        // throw err;
        return ReE(response, err.message, 500)
    }
}

const json = await = fetch(...).then(safeParseJSON)
like image 25
tokland Avatar answered Oct 15 '22 13:10

tokland