NodeJs actual combat - to-do list 4 - solve the Chinese garbled problem of to-do items
Where does the garbled code problem arise?
Run the server.js in Section 3, when adding Chinese to-do items, Chinese garbled characters will occur. Garbled characters may occur in the following places:
- When sending request package parameters
- Parameters are transmitted to the background, and garbled characters occur during parsing
- Garbled characters occur when the data is read and returned to the foreground for serialization
Locating garbled characters
Don't panic if you encounter problems, first debug to see
VSCode starts NodeJs debugging mode
- First locate server.js in the left navigation bar, just click with the left mouse button
- Run server.js in debug mode, run -> start debugging, or use the shortcut key F5
to start debugging, and find that the port is occupied
Execute the following command to see which process occupies the port netstat -ano|findstr 3000
C:\Users\Administrator>netstat -ano|findstr 3000
TCP 127.0.0.1:3000 0.0.0.0:0 LISTENING 85772
TCP 127.0.0.1:3000 127.0.0.1:57460 ESTABLISHED 85772
TCP 127.0.0.1:57460 127.0.0.1:3000 ESTABLISHED 67588
Use the taskkill command to kill a process
C:\Users\Administrator>taskkill /pid 85772
错误: 无法终止 PID 为 85772 的进程。
原因: 只能强行终止这个进程(带 /F 选项)。
C:\Users\Administrator>taskkill /pid /f 85772
错误: 无效语法。需要 '/pid' 的值。
键入 "TASKKILL /?" 以了解用法。
C:\Users\Administrator>taskkill /f /pid 85772
成功: 已终止 PID 为 85772 的进程。
C:\Users\Administrator>taskkill /f /pid 67588
成功: 已终止 PID 为 67588 的进程。
Start the debugging again, and the debugging window will appear.
3. Add a breakpoint in front of the code to be debugged, just click the mouse, and
a small red dot will appear in front of the code
- Added Chinese item to the page
and found that it was garbled when passing through the front end
Debug JS in browser
Open the browser developer mode, and first look at the parameters passed by the Network. The
garbled parameters are %E4%B8%AD%E6%96%872222. We debug js in the browser console. Methods related to encoding include encodeURI and decodeURI. Debugging this method, we can see that the Chinese 2222 url has passed the encodeURI and becomes %E4%B8%AD%E6%96%872222.
There is a way to decode it when the backend receives it, so modify server.js
function findItemData(urlParse) {
if (urlParse.query.length > 0) {
var queryArray = urlParse.query.split('=');
if (queryArray.length >= 2) {
return decodeURI(queryArray[1]);
}
}
return '';
}
After saving, restart the debugging and find that the decoding is successful
renderings
execute add
- add 1111
- add en1111
- Add Chinese 11111
Execution completed
- complete 1111
- complete en1111
- Completion of Chinese 1111