In Node.js, we often encounter the problem of garbled query results. The main reason for this problem is that in Node.js, the server uses UTF-8 encoding by default, but the database uses GBK encoding by default. Therefore, after executing the query operation, garbled characters will appear. This article will introduce in detail how to solve the problem of garbled query results in Node.js.
1. Understand UTF-8 and GBK encoding
UTF-8 encoding is a byte-encoded Unicode encoding method. This encoding method is currently the most widely used Unicode encoding method. It uses single-byte, double-byte, and three-byte encodings of different lengths to represent characters.
GBK encoding is an encoding method like ASCII code. It uses double-byte encoding and can accommodate a maximum of 21886 Chinese characters. GBK encoding was originally developed by Microsoft and was later designated as the Chinese encoding standard by the National Bureau of Standards.
2. Solution
When performing query operations, we can set the character set of the response header so that Query results can be parsed correctly. The following is a sample code for setting the response header character set:
res.writeHead(200, {"Content-Type": "text/html;charset=utf-8"});
Note: Although this method can solve the problem of garbled characters, it is not the best solution. Unless there are special circumstances, we should generally not use this method.
We can set the connection character set to UTF-8 before connecting to the database. The following is a sample code for setting the connection character set:
var connection = mysql.createConnection({ host: 'localhost', user: 'root', password: '', database:'test', port: 3306, charset : 'utf8mb4' });
Note: This method needs to be set every time you connect to the database, which is more troublesome.
We can set the database character set to UTF-8 when creating the database. The following is a sample code for setting the database character set:
CREATE DATABASE my_db DEFAULT CHARACTER SET utf8mb4 DEFAULT COLLATE utf8mb4_general_ci;
Note: This method needs to be set every time the database is created, and is applicable to fewer scenarios.
We can modify the my.cnf configuration file and set the default character set of the database to UTF-8. The following is an example of modifying the my.cnf configuration file:
[mysqld] init_connect='SET collation_connection = utf8mb4_unicode_ci' init_connect='SET NAMES utf8mb4' character-set-server=utf8mb4 collation-server=utf8mb4_unicode_ci
Note: This method is relatively complex and requires modifying the configuration file, which may have an impact on other configurations.
3. Summary
The above are several methods to solve the problem of garbled Node.js query results. According to the actual needs and environment, choose a method that suits you.
The above is the detailed content of What to do if nodejs query results are garbled. For more information, please follow other related articles on the PHP Chinese website!