Home > Article > Web Front-end > What should I do if node.js outputs Chinese garbled characters?
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.
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).
# (3) When the client receives the string content sent by the server, a parsing error occurs, resulting in 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('<head><meta charset="utf-8"/></head>');
Option 2 (recommended): Use the setHeader method to only set the request header.
resp.setHeader('Content-Type','text/html; charset=utf-8');
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!