Garbled Chinese characters received by nodejs
With the development of the Internet, many developers have begun to use Node.js for back-end development. However, some developers will encounter the problem of garbled Chinese characters when using Node.js to receive Chinese characters. This question is both confusing and difficult. This article will introduce the problem of garbled Chinese characters received by Node.js and provide several solutions.
Problem description
When using Node.js to receive requests containing Chinese characters, sometimes garbled characters will appear, as shown in the following figure:
As shown in the figure above, the received request parameters contain Chinese characters, but they are converted into garbled characters. This is obviously not the result we want, so where is the problem?
Problem Analysis
First of all, we need to understand the principle of Node.js receiving request parameters.
Node.js is a high-performance platform based on event-driven and non-blocking I/O models. It listens to the network port. When a request is received, it triggers an event and encapsulates the request into a request object. The request object contains request headers, request body and other information. When receiving the request body, Node.js uses UTF-8 encoding for decoding by default.
So, if the request body we receive contains Chinese characters, and the Content-Type in the request header does not set the character set encoding, UTF-8 will be used for decoding by default. If characters are set in the request header Set encoding, a specific character set will be used for decoding. However, if the character set encoding is not set in the request header and the request body contains multiple character set encodings or garbled characters, Node.js may cause garbled characters when decoding.
Solution
For the problem of garbled Chinese characters received by Node.js, we can start from the following aspects:
- Uniform Character Set Encoding
In order to avoid the problem of inconsistent character set encoding, we can set a unified character set encoding in the request header.
For example, we can set in the request header:
Content-Type: application/x-www-form-urlencoded;charset=utf-8
In this way, when receiving a request body containing Chinese characters in Node.js, it can be decoded uniformly by using UTF-8 encoding .
- Forcing the character set encoding to be specified
In addition to setting the character set encoding in the request header, we can also force the character set encoding to be specified for decoding.
For example, when using the express framework, we can use the body-parser middleware and specify the character set encoding for decoding. The example is as follows:
const bodyParser = require('body-parser') const app = express() app.use(bodyParser.urlencoded({ extended: false, limit: '50mb', parameterLimit: 10000, type: 'application/x-www-form-urlencoded', verify: (req, res, buf) => { req.raw = buf } }))
- Use the iconv-lite module to decode
Another method is to use the iconv-lite module to decode, the code example is as follows:
const iconv = require('iconv-lite') const buffer = Buffer.from('e4b8ade69687', 'hex') const str = iconv.decode(buffer, 'utf8') console.log(str) // 输出:"中文"
- Use the text-encoding module for decoding
The last solution is to use the text-encoding module for decoding.
For example, when using the express framework, we can use the text-encoding decoder for our request body parser and set it to utf-8. An example is as follows:
const express = require('express') const bodyParser = require('body-parser') const { TextDecoder } = require('text-encoding') const app = express() app.use(bodyParser.json({ verify: function(req, res, buf) { req.body = JSON.parse(new TextDecoder('utf-8').decode(buf)) }}))
Summary
This article introduces the garbled problem that may occur when Node.js receives a request containing Chinese characters, and several methods to solve this problem.
In Node.js development, it is very important to correctly handle the problem of garbled Chinese characters. To solve this problem, we can use unified character set encoding, forcefully specify character set encoding, use the iconv-lite module to decode, and use the text-encoding module to decode, etc., so as to avoid garbled characters and ensure the normal operation of the application. I hope this article can help developers solve this problem.
The above is the detailed content of Garbled Chinese characters received by nodejs. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



React combines JSX and HTML to improve user experience. 1) JSX embeds HTML to make development more intuitive. 2) The virtual DOM mechanism optimizes performance and reduces DOM operations. 3) Component-based management UI to improve maintainability. 4) State management and event processing enhance interactivity.

Article discusses connecting React components to Redux store using connect(), explaining mapStateToProps, mapDispatchToProps, and performance impacts.

The article discusses defining routes in React Router using the <Route> component, covering props like path, component, render, children, exact, and nested routing.

Vue 2's reactivity system struggles with direct array index setting, length modification, and object property addition/deletion. Developers can use Vue's mutation methods and Vue.set() to ensure reactivity.

Redux reducers are pure functions that update the application's state based on actions, ensuring predictability and immutability.

The article discusses Redux actions, their structure, and dispatching methods, including asynchronous actions using Redux Thunk. It emphasizes best practices for managing action types to maintain scalable and maintainable applications.

TypeScript enhances React development by providing type safety, improving code quality, and offering better IDE support, thus reducing errors and improving maintainability.

React components can be defined by functions or classes, encapsulating UI logic and accepting input data through props. 1) Define components: Use functions or classes to return React elements. 2) Rendering component: React calls render method or executes function component. 3) Multiplexing components: pass data through props to build a complex UI. The lifecycle approach of components allows logic to be executed at different stages, improving development efficiency and code maintainability.
