Home >Web Front-end >Front-end Q&A >What should I do if node.js outputs Chinese garbled characters?

What should I do if node.js outputs Chinese garbled characters?

藏色散人
藏色散人Original
2022-11-08 16:13:572080browse

Solution to the Chinese garbled output from node.js: 1. Use the writeHeader and write methods to write the format settings into the request header and html interface; 2. Use "resp.setHeader('Content-Type' ,'text/html; charset=utf-8');" method to set the request header.

What should I do if node.js outputs Chinese garbled characters?

The operating environment of this tutorial: Windows 7 system, node18.4.0 version, Dell G3 computer.

What should I do if node.js outputs Chinese garbled characters?

Solution to garbled characters generated by using Chinese in Node.js

Project scenario:

Node.js Overview: One based on Chrome JavaScript A platform built at runtime. Node.js is an event-driven I/O server-side JavaScript environment based on Google's V8 engine. The V8 engine executes Javascript very quickly and has very good performance.

Scenarios in Node: Node.js has many tools that help develop server-side web applications. Chinese characters are often used in Node.js. And will cause garbled code problems.

Problem description

The problem occurs when the client accesses the server. The process is as follows:

(1) The client sends a Get request to the server .

(2) The server side obtains the client's url address and method method. and send the result back to the client (using the res.end method).

What should I do if node.js outputs Chinese garbled characters?

# (3) When the client receives the string content sent by the server, a parsing error occurs, resulting in garbled characters.

What should I do if node.js outputs Chinese garbled characters?

Cause analysis:

The server-side encoding format is not specified. You need to set the encoding format to UTF-8 to solve this problem.

Solution:

Solution 1: Use the writHeader and write methods to write the format settings into the request header and html interface.

resp.writeHeader(200, {'Content-Type' : 'text/html;charset:utf-8'});
resp.write(&#39;<head><meta charset="utf-8"/></head>&#39;);

Option 2 (recommended): Use the setHeader method to only set the request header.

resp.setHeader(&#39;Content-Type&#39;,&#39;text/html; charset=utf-8&#39;);

What should I do if node.js outputs Chinese garbled characters?

Recommended learning: "nodejs video tutorial"

The above is the detailed content of What should I do if node.js outputs Chinese garbled characters?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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
Previous article:What is node.redNext article:What is node.red