1. 程式人生 > >解決node裏面的中文亂碼

解決node裏面的中文亂碼

學習 後來 啟動 head 資料 代碼 html har count

今天咋學習node的時候,跟著視頻裏在擼代碼,但是卻出現了中文亂碼的情況,視頻中的谷歌瀏覽器可能和我的版本不一致,先看代碼吧:

‘use strict‘;
const http = require("http");
let count = 0;
const server = http.createServer((req, res) => {
    res.write(`這是第${count++}個訪問的`);
    res.end();
});
server.listen(2080, error => {
    if (error)
        throw error;
    console.log("啟動成功")
});

  我是想用node建一個本地的服務器,然後統計訪問的個數,但是卻出現了中文亂碼:

榪欐槸絎?0涓闂殑

後來查詢資料,原來加一個頭部代碼就行:
設置 res.writeHead(200, {‘Content-Type‘: ‘text/html; charset=utf-8‘});
‘use strict‘;
const http = require("http");
let count = 0;
const server = http.createServer((req, res) => {
    res.writeHead(200, {‘Content-Type‘: ‘text/html; charset=utf-8‘});
    res.write(`這是第${count++}個訪問的`);
    res.end();
});
server.listen(2080, error => {
    if (error)
        throw error;
    console.log("啟動成功")
});

  

解決node裏面的中文亂碼