Home Web Front-end Front-end Q&A Garbled Chinese characters received by nodejs

Garbled Chinese characters received by nodejs

May 08, 2023 am 09:33 AM

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:

  1. 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
Copy after login

In this way, when receiving a request body containing Chinese characters in Node.js, it can be decoded uniformly by using UTF-8 encoding .

  1. 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 } }))
Copy after login
  1. 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) // 输出:"中文"
Copy after login
  1. 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)) }}))
Copy after login

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!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

React's Role in HTML: Enhancing User Experience React's Role in HTML: Enhancing User Experience Apr 09, 2025 am 12:11 AM

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.

How do you connect React components to the Redux store using connect()? How do you connect React components to the Redux store using connect()? Mar 21, 2025 pm 06:23 PM

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

How do you define routes using the <Route> component? How do you define routes using the <Route> component? Mar 21, 2025 am 11:47 AM

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

What are the limitations of Vue 2's reactivity system with regard to array and object changes? What are the limitations of Vue 2's reactivity system with regard to array and object changes? Mar 25, 2025 pm 02:07 PM

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.

What are Redux reducers? How do they update the state? What are Redux reducers? How do they update the state? Mar 21, 2025 pm 06:21 PM

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

What are Redux actions? How do you dispatch them? What are Redux actions? How do you dispatch them? Mar 21, 2025 pm 06:21 PM

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.

What are the benefits of using TypeScript with React? What are the benefits of using TypeScript with React? Mar 27, 2025 pm 05:43 PM

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

React Components: Creating Reusable Elements in HTML React Components: Creating Reusable Elements in HTML Apr 08, 2025 pm 05:53 PM

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.

See all articles