NodeJS系列~第二個小例子,解決中文亂碼的問題


返回目錄

為了使頁面支持的字符更多,所以編碼使用UTF-8,注意,你的原js文件的編碼也要是utf-8的,可以通過記事本進行編碼的修改

然后在你的js服務端添加網頁響應頭信息,把charset:utf8添加到頭中,代碼如下

function start(response, request) {
    var getQuery = url.parse(request.url).query;
    var getData = qs.parse(getQuery); //getData數據 
    var body =
       '<form action="/upload" enctype="multipart/form-data" ' +
       'method="post">' +
       '選擇文件:<input type="file" name="upload" multiple="multiple">' +
       '<input type="submit" value="Upload file">' +
       '</form>';
    response.writeHead(200, { 'Content-Type': 'text/html;charset=utf-8' });
    // response.write(getData["jsonpcallback"] + "({result:'" + body + "'})");//輸出json
    response.write(body);//輸出字符串
    response.end();
}

當然訪問這個頁面時,中文就可以順序的顯示出來了,呵呵

小知識,一般為了隱藏圖像文件的地址,或者統一為圖像添加某些信息(如文字,水紋等),我們會通過一個網頁來響應圖像文件,你可以將圖像ID傳入網頁,然后網頁以  "Content-Type": "image/jpg"的格式進行響應即可

//顯示圖像
function show(response, request) {
    console.log('request handler \'show\' was called...')
    console.log("read image:" + filename);
    fs.readFile(filename, "binary", function (error, file) {
        if (error) {
            response.writeHead(500, {
                "Content-Type": "text/plain"
            });
            response.write(error + "\n");
            response.end();
        } else {
            response.writeHead(200, {
                "Content-Type": "image/jpg"
            });
            response.write(file, "binary");
            response.end();
        }
    });
}

結果如圖:

 

返回目錄


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM