English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Solution to the Problem of Garbled Characters in HTML Return Value When Using HTTP Request in Node.js

Today, when I used nodejs to make an http request, the returned data was an HTML file, and I still used the method I used before to parse JSON data. As expected, an error occurred: SyntaxError: Unexpected token  in JSON at position 0

There is no way, so I had to change a method, converting the received Buffer object to a string, only to find out it was garbled.

The first feeling is encoding problem, google it and look at the official documentation, summarize three methods:

1, toString with encoding format as a parameter.

2, use iconv-, change encoding of lite.

3, use cheerio to load html.

However, none of the three methods above are the cause of my error, and then I saw that there was a similar problem in cnode, although not exactly the same, but some of the answers mentioned using gzip compression, and after receiving it, not decompressing it will cause garbled characters, and indeed I found gzip compression = = manual face in my request header.

Knowing where the problem is, it's very convenient to solve it.

First, let's npm install zlib.

Then import var zlib = require('zlib'); in the header.

Then check the official documentation and find that there are two ways to decompress, one is synchronous, and the other is asynchronous.

I'll use asynchronous method here.

zlib.unzip(chunk, function(error, res) {
  console.log(error);
  console.log(res+""
});

Here, the chunk is our received buffer object. It should be noted that this asynchronous callback has two parameters, the first is the error message, and the second is the html string we need.

If you need to use synchronous, please call zlib.unzipSync(buffer); ps: it showed an error when I tested. Error: unexpected end of file

Alright, that's it. My problem is perfectly solved.

This article solves the problem of乱码 when the return value of http request in nodejs is html, which is all the content I share with everyone. I hope it can be a reference for everyone, and I also hope everyone will support the呐喊 tutorial more.

You May Also Like