Answer the question
In order to leave comments, you need to log in
Why does the Unexpected token in JSON error occur very often?
Unexpected token : in JSON at position 2539.
Positions are always different, characters are also different.
The bottom line is that a script is running that very often accesses the Api of one site, and such an error occurs in about 5% of requests, and if you send exactly the same request again, there will be no error.
var options = {
host: 'example.com',
path: '/path'
};
var request = http.get(options, function(res) {
let rawData = '';
res.on('data', (chunk) => rawData += chunk);
res.on('end', () => {
try {
let parsedData = JSON.parse(rawData);
} catch (e) {
console.log(e.message);
}
});
});
Answer the question
In order to leave comments, you need to log in
More or less like this
var request = http.get(options, function(res) {
let rawData = [];
res.on('data', (chunk) => rawData.push(chunk));
res.on('end', () => {
rawData = Buffer.concat(rawData).toString();
try {
let parsedData = JSON.parse(rawData);
} catch (e) {
console.log(e.message);
}
});
});
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question