Node响应中文时解决乱码问题
生活随笔
收集整理的這篇文章主要介紹了
Node响应中文时解决乱码问题
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
場景
在使用node響應(yīng)英文時可以在app.js中這樣寫
//代碼塊: node-http-server//表示引入http模塊 var http = require('http'); /*request??? 獲取客戶端傳過來的信息response? 給瀏覽器響應(yīng)信息 */ http.createServer(function (request, response) {//設(shè)置響應(yīng)頭response.writeHead(200, {'Content-Type': 'text/plain'});//表示給我們頁面上面輸出一句話并且結(jié)束響應(yīng)response.end('Hello World '); }).listen(8081);? //端口console.log('Server running at http://127.0.0.1:8081/');但是如果想響應(yīng)中文,即將代碼改為如下
//代碼塊: node-http-server//表示引入http模塊 var http = require('http'); /*request??? 獲取客戶端傳過來的信息response? 給瀏覽器響應(yīng)信息 */ http.createServer(function (request, response) {//設(shè)置響應(yīng)頭response.writeHead(200, {'Content-Type': 'text/plain'});//表示給我們頁面上面輸出一句話并且結(jié)束響應(yīng)response.end('霸道的程序猿'); }).listen(8081);? //端口console.log('Server running at http://127.0.0.1:8081/');運(yùn)行效果
?
注:
博客:
https://blog.csdn.net/badao_liumang_qizhi
關(guān)注公眾號
霸道的程序猿
獲取編程相關(guān)電子書、教程推送與免費(fèi)下載。
實現(xiàn)
可以通過如下兩行設(shè)置響應(yīng)頭
res.writeHead(200,{"Content-type":"text/html;charset='utf-8'"}); //解決亂碼res.write("<head> <meta charset='UTF-8'></head>");? //解決亂碼完整示例代碼
const http =require('http');/*req?? 獲取客戶端傳過來的信息res? 給瀏覽器響應(yīng)信息 */http.createServer((req,res)= >{console.log(req.url);? //獲取url//設(shè)置響應(yīng)頭//狀態(tài)碼是 200,文件類型是 html,字符集是 utf-8res.writeHead(200,{"Content-type":"text/html;charset='utf-8'"}); //解決亂碼res.write("<head> <meta charset='UTF-8'></head>");? //解決亂碼res.write('公眾號:霸道的程序猿');res.write('<h2>公眾號:霸道的程序猿</h2>');res.end();? //結(jié)束響應(yīng)}).listen(3000);效果
?
總結(jié)
以上是生活随笔為你收集整理的Node响应中文时解决乱码问题的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Node中的Http模块和Url模块的使
- 下一篇: Node中自启动工具supervisor