日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學(xué)無(wú)先后,達(dá)者為師

網(wǎng)站首頁(yè) 前端文檔 正文

node.js解決客戶(hù)端請(qǐng)求數(shù)據(jù)里面中文亂碼的事件方法_node.js

作者:勇敢*牛牛 ? 更新時(shí)間: 2022-03-21 前端文檔

node.js解決客戶(hù)端請(qǐng)求數(shù)據(jù)里面中文亂碼的事件

例如代碼:

var http = require('http');
var server = http.createServer();
server.on('request',function(req,res){
    // res.end("hello world");
    res.end("你好 世界");
});
server.listen(3000,function(){
    console.log("Server is running");
});

在這里插入圖片描述

原因:

在服務(wù)端默認(rèn)發(fā)送的數(shù)據(jù),其實(shí)是UFT8編碼內(nèi)容

但是瀏覽器不知道你是UFT8編碼內(nèi)容

瀏覽器在不知道服務(wù)器響應(yīng)內(nèi)容的編碼情況下會(huì)按照當(dāng)前操作系統(tǒng)的默認(rèn)編碼去執(zhí)行

中文操作系統(tǒng)默認(rèn)是GBK

解決方法:正確是告訴瀏覽器我給你發(fā)送的是什么類(lèi)型的數(shù)據(jù)res.setHeader('Content-Type','text/plain;charset=utf-8');內(nèi)容類(lèi)型,注意連接符不要寫(xiě)錯(cuò),utf-8也不要亂寫(xiě)。在http協(xié)議中,content-Type就是用來(lái)告知對(duì)方我給你發(fā)送的數(shù)據(jù)內(nèi)容是什么類(lèi)型,然后后面就是緊跟著寫(xiě)上類(lèi)型

var http = require('http');
var server = http.createServer();
server.on('request',function(req,res){
    // res.end("hello world");
    res.setHeader('Content-Type','text/plain;charset=utf-8');
    res.end("你好 世界");
});
server.listen(3000,function(){
    console.log("Server is running");
});

在這里插入圖片描述
注意這里的類(lèi)型有很多種

響應(yīng)內(nèi)容類(lèi)型Content-Type

var http = require('http');
var server = http.createServer();
server.on('request',function(req,res){
    if(req.url==='/plain'){
        res.setHeader('Content-Type','text/plain;charset=utf-8');
        res.end("你好 世界");
    }else if(req.url==='/html'){
        res.setHeader('Content-Type','text/html;charset=utf-8');
        res.end("<h1>你好 世界<br/> hello world</h1>");
    }
   
});
server.listen(3000,function(){
    console.log("Server is running");
});

根據(jù)不同請(qǐng)求路徑返回不同的類(lèi)型Content-Type格式

在這里插入圖片描述

原文鏈接:https://blog.csdn.net/m0_46672781/article/details/122222735

欄目分類(lèi)
最近更新