Nodejs?http模塊返回內(nèi)容中文亂碼問題及解決
Nodejs http模塊返回內(nèi)容中文亂碼
當(dāng)調(diào)用rs.end()方法,向客戶端發(fā)送中文內(nèi)容的時候,會出現(xiàn)亂碼問題,此時,需要手動設(shè)置內(nèi)容的編碼格式:
修改完后記得重新運(yùn)行代碼
server.on('request', (req, res) => {
const url = req.url
const method = req.method
const s = `請求的url是 ${url}, 請求方法是 ${method}`
console.log(s)
// 調(diào)用res.end()方法,向服務(wù)器響應(yīng)一些內(nèi)容
res.setHeader("Content-Type", 'text/html; charset=utf-8')
res.end(s)
})可以看到返回的內(nèi)容已經(jīng)被修改成功

Nodejs 模塊使用 http、url
1.安裝插件
在vsCode中安裝插件Node Snippets后,有node提示
輸入node根據(jù)提示文本選擇node-http-server可以快速生成請求代碼

var http = require('http');
http.createServer(function (request, response) {
response.writeHead(200, {'Content-Type': 'text/plain'});
response.end('Hello World');
}).listen(8081);
console.log('Server running at http://127.0.0.1:8081/');2.http和url模塊的應(yīng)用
url的方法:http://nodejs.cn/api/url.html
url.parse(urlString[,,])? //解析url地址 url.format()//parse的反向操作 url.resolve(from,to);//添加或者替換地址
url.resolve('/one/two/three', 'four'); // '/one/two/four'
url.resolve('http://example.com/', '/one'); // 'http://example.com/one'var http = require('http');//引入http模塊
const url = require('url')
//http://127.0.0.1:3000?name=zhangsan&age=20 獲取get傳過來的值
/**
* request 獲取瀏覽器客戶端傳過來的信息
* response服務(wù)器響應(yīng)的信息
*/
http.createServer(function (request, response) {
//設(shè)置響應(yīng)頭,包括狀態(tài)碼200,請求的文本類型,字符集是utf-8
response.writeHead(200, {'Content-Type': 'text/html;charset="utf-8"'});
response.write("<head><meta charset='UTF-8'></head>")//解決中文亂碼
// console.log(request.url);//獲得瀏覽器請求的地址
if(request.url!='/favicon.ico'){
//避免在瀏覽器地址欄輸入url后服務(wù)器不斷返回/favicon.ico地址
var userInfo = url.parse(request.url,true).query;
console.log(userInfo)
console.log(`姓名:${userInfo.name}--年齡:${userInfo.age}`)
}
response.end('response finish!');//結(jié)束響應(yīng),必須調(diào)用,不然瀏覽器回一直處于響應(yīng)狀態(tài)
}).listen(3000);
console.log('Server running at http://127.0.0.1:3000/');
//var api = 'http://127.0.0.1:3000?name=zhangsan&age=20'
// console.log(url.parse(api,true));//設(shè)置為ture,將返回的值解析為對象
// var getValue=url.parse(api,true).query;
// console.log(getValue);//獲得url傳過來的值
// console.log(`姓名:${getValue.name}--年齡:${getValue.age}`)運(yùn)行上面代碼后,在瀏覽器中手動輸入get請求
http://127.0.0.1:3000?name=zhangsan&age=20'
命令行中能返回

總結(jié)
以上為個人經(jīng)驗(yàn),希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
koa-compose簡單實(shí)現(xiàn)及使用的妙處
這篇文章主要為大家介紹了koa-compose簡單實(shí)現(xiàn)及使用的妙處詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-04-04
nodejs+socket.io實(shí)現(xiàn)p2p消息實(shí)時發(fā)送的項(xiàng)目實(shí)踐
本文主要介紹了nodejs+socket.io實(shí)現(xiàn)p2p消息實(shí)時發(fā)送,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2022-06-06
nodejs require js文件入口,在package.json中指定默認(rèn)入口main方法
今天小編就為大家分享一篇nodejs require js文件入口,在package.json中指定默認(rèn)入口main方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-10-10
Nodejs 和Session 原理及實(shí)戰(zhàn)技巧小結(jié)
這篇文章主要介紹了Nodejs 和Session 原理及實(shí)戰(zhàn)技巧小結(jié),需要的朋友可以參考下2017-08-08

