Reputation: 1309
I'm getting a JSON parsing error when I try to fetch data from a server endpoint.
It's the first time that Axios cannot decode the JSON response automatically.
Debugging my code, I've seen that Axios catch some unexpected character in the server response that makes the JSON not valid.
7F5
{
"message": "OK"
...cut
}
0
Error:
(node:14940) UnhandledPromiseRejectionWarning: SyntaxError: Unexpected token F in JSON at position 1
I suppose that could be a charset encoding problem.
Axios client configuration:
const pclClient = axios.create({
baseURL: "http://server/endpoint",
responseType: "json",
responseEncoding: "utf8",
headers: {
Accept: "application/json",
"Content-Type": "application/json",
charset: "utf-8"
}
});
Using tools like postman or Chrome Extension Advanced Request Client, the problem is not present.
Can someone help me?
Upvotes: 0
Views: 6322
Reputation: 1309
The problem comes from transfer-encoding: chunked
response header.
RFC 7230 tells that "A recipient MUST be able to parse and decode the chunked transfer coding."
At the moment, Axios don't handle chunked responses (transfer-encoding chunked not handled for application/json)
To resolve this issue, I've made a chunk parser using regex to removing chunk's info.
const pclClient = axios.create({
baseURL: "http://server/",
responseType: "json",
headers: {
Accept: "application/json"
}
});
const chunksParser = body => {
return body
.replace(/^(\w{1,3})\r\n/, "") // replace header chunks info
.replace(/\r\n(\w{1,3})\r\n/, "") // replace in-body chunks info
.replace(/(\r\n0\r\n\r\n)$/, ""); // replace end chunks info
};
const getData = async () => {
response = await pclClient.get("data.json");
const { data } = response;
const body = chunksParser(data);
const json = JSON.parse(body);
return json;
};
I was looking for a built-in function inside Axios. I hope it will be available in the future.
Thank you for commenters that helped me to understand what was the problem.
Upvotes: 4