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?
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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With