0

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?

8
  • Try remove responseEncoding , charset Commented Feb 17, 2020 at 11:59
  • Your message beginning with 7F5 isn't valid JSON. Commented Feb 17, 2020 at 12:00
  • @haongdv. Removed but I've always the problem. Thank you for your comment. Commented Feb 17, 2020 at 12:03
  • 2
    That looks like chunked HTTP, except that the content is not 2037 (0x7F5) bytes long. The details of chunked HTTP should normally by handled by the HTTP client. Commented Feb 17, 2020 at 14:47
  • 1
    Interesting thread here. Please do take the time to write an "Answer" when you've solved it. Commented Feb 17, 2020 at 16:01

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.