node.js使用http模塊創(chuàng)建服務(wù)器和客戶端完整示例
本文實例講述了node.js使用http模塊創(chuàng)建服務(wù)器和客戶端。分享給大家供大家參考,具體如下:
node.js中的 http 模塊提供了創(chuàng)建服務(wù)器和客戶端的方法,http 全稱是超文本傳輸協(xié)議,基于 tcp 之上,屬于應(yīng)用層協(xié)議。
一、創(chuàng)建http服務(wù)器
const http = require('http'); //創(chuàng)建一個http服務(wù)器 let server = http.createServer(); //監(jiān)聽端口 server.listen(8888, '0.0.0.0'); //設(shè)置超時時間 server.setTimeout(2 * 60 * 1000); //服務(wù)器監(jiān)聽時觸發(fā) server.on('listening', function () { console.log('監(jiān)聽開始'); }); //接收到客戶端請求時觸發(fā) server.on('request', function (req, res) { //req表示客戶端請求對象,是http.IncomingMessage類的實例,可讀流。 //res表示服務(wù)端響應(yīng)對象,是http.ServerResponse類的實例,可寫流。 //請求方法 console.log(req.method); //請求url console.log(req.url); //請求的頭信息 console.log(req.headers); //請求的http版本 console.log(req.httpVersion); //請求對象的socket對象 console.log(req.socket); res.end('hello'); }); //連接建立時觸發(fā) server.on('connection', function (socket) { console.log('建立連接'); }); //客戶端向服務(wù)器發(fā)送CONNECT請求時觸發(fā) server.on('connect', function (req, socket, head) { console.log('客戶端connect'); }); //服務(wù)器關(guān)閉時觸發(fā),調(diào)用 close() 方法。 server.on('close', function () { console.log('服務(wù)器關(guān)閉'); }); //發(fā)生錯誤時觸發(fā) server.on('error', function (err) { console.log(err); }); //如果連接超過指定時間沒有響應(yīng),則觸發(fā)。 //超時后,不可再復(fù)用已建立的連接,需發(fā)請求重新建立連接 server.on('timeout', function (socket) { console.log('連接已超時'); });
請求對象 req 里保存了客戶端的詳細信息,包括 url,請求參數(shù)等,為了方便的解析這些參數(shù),我們可以使用 url.parse() 方法。
const http = require('http'); const url = require('url'); //創(chuàng)建一個http服務(wù)器 let server = http.createServer(); //監(jiān)聽端口 server.listen(8888, '0.0.0.0'); //接收到客戶端請求時觸發(fā) server.on('request', function (req, res) { //解析url返回一個url對象 //如果參數(shù)二設(shè)為true,則url對象中的query屬性將通過querystring.parse()生成一個對象 let params = url.parse(req.url, true); //完整url地址 console.log('href', params.href); //主機名,包含端口 console.log('host', params.host); //主機名,不包含端口 console.log('hostname', params.hostname); //端口 console.log('port', params.port); //協(xié)議 console.log('protocol', params.protocol); //路徑,包含查詢字符串 console.log('path', params.path); //路徑,不包含查詢字符串 console.log('pathname', params.pathname); //查詢字符串,不包含 ? console.log('query', params.query); //查詢字符串,包含 ? console.log('search', params.search); //散列字符串,包含 # console.log('hash', params.hash); res.end('end'); });
響應(yīng)對象 res 可以設(shè)置服務(wù)器響應(yīng)給客戶端的一些參數(shù)。
const http = require('http'); const url = require('url'); //創(chuàng)建一個http服務(wù)器 let server = http.createServer(); //監(jiān)聽端口 server.listen(8888, '0.0.0.0'); //接收到客戶端請求時觸發(fā) server.on('request', function (req, res) { //設(shè)置響應(yīng)頭信息 res.setHeader('Content-Type', 'text/html;charset=utf-8'); //獲取響應(yīng)頭信息 res.getHeader('Content-Encoding'); res.setHeader('test', 'test'); //刪除響應(yīng)頭信息 res.removeHeader('test'); //判斷響應(yīng)頭是否已發(fā)送 console.log(res.headersSent ? '已發(fā)送' : '未發(fā)送'); //注意writeHead()與setHeader()的區(qū)別,setHeader()并不會立即發(fā)送響應(yīng)頭。 //而writeHead()會發(fā)送,writeHead()設(shè)置的響應(yīng)頭比setHeader()的優(yōu)先。 res.writeHead(200, { 'aaa': 'aaa' }); //判斷響應(yīng)頭是否已發(fā)送 console.log(res.headersSent ? '已發(fā)送' : '未發(fā)送'); //如何不發(fā)送日期 Date,設(shè)置為false將不發(fā)送Date res.sendDate = false; //設(shè)置響應(yīng)的超時時間 res.setTimeout(30 * 1000); res.on('timeout', function () { console.log('響應(yīng)超時'); }); //向客戶端發(fā)送數(shù)據(jù) //由于res響應(yīng)對象也是一個流,所以可以使用write()來寫數(shù)據(jù) res.write(Buffer.from('你好')); res.write(Buffer.from('歡迎')); res.end('end'); });
二、http的客戶端
有些時候我們需要通過get或post去請求其它網(wǎng)站的資源或接口,這個時候就需要用到http客戶端了。
const http = require('http'); const zlib = require('zlib'); let client = http.request({ //協(xié)議 'protocol': 'http:', //主機名或IP 'hostname': 'www.baidu.com', //端口 'port': 80, //請求方式 'method': 'GET', //請求路徑和查詢字符串 'path': '/', //請求頭對象 'headers': { 'Accept-Encoding': 'gzip, deflate, br' }, //超時時間 'timeout': 2 * 60 * 1000 }); //發(fā)送請求 client.end(); //響應(yīng)被接收到時觸發(fā) client.on('response', function (res) { console.log('狀態(tài)嗎:' + res.statusCode); console.log('響應(yīng)頭:' + JSON.stringify(res.headers)); //頭信息的名稱為小寫 let encoding = res.headers['content-encoding']; //判斷響應(yīng)頭中的內(nèi)容編碼,是否有過壓縮,如果有則進行解壓 if (encoding.match(/\bgzip\b/)) { res.pipe(zlib.createGunzip()).pipe(process.stdout); } else if (encoding.match(/\bdeflate\b/)) { res.pipe(zlib.createInflate()).pipe(process.stdout); } else { res.pipe(process.stdout); } }); //請求過程中出錯了觸發(fā) client.on('error', function (err) { console.log(err); }); //當(dāng) socket 被分配到請求后觸發(fā) client.on('socket', function (socket) { socket.setTimeout(2 * 60 * 1000); socket.on('timeout', function () { //終止本次請求 client.abort() }); });
也可以使用 http.get() 簡便方法進行 get 請求。
const http = require('http'); //會自動調(diào)用 req.end(),默認為 get 請求。 http.get('http://www.baidu.com', function (res) { res.on('data', function (data) { console.log(data.toString()); }); });
希望本文所述對大家node.js程序設(shè)計有所幫助。
- Node.js使用http模塊實現(xiàn)后臺服務(wù)器流程解析
- Node.js?搭建后端服務(wù)器內(nèi)置模塊(?http+url+querystring?的使用)
- Node.js基礎(chǔ)入門之path模塊,url模塊,http模塊使用詳解
- 基于Node.js的http模塊搭建HTTP服務(wù)器
- Node.js進階之核心模塊https入門
- node.js中http模塊和url模塊的簡單介紹
- node.js 核心http模塊,起一個服務(wù)器,返回一個頁面的實例
- Node.js中Request模塊處理HTTP協(xié)議請求的基本使用教程
- Node.js 中 http 模塊的深度剖析與實戰(zhàn)應(yīng)用小結(jié)
相關(guān)文章
node?NPM庫qs?iconv-lite字符串編碼轉(zhuǎn)換及解析URL查詢學(xué)習(xí)
這篇文章主要為大家介紹了node?NPM庫之qs解析URL查詢字符串及iconv-lite字符串編碼轉(zhuǎn)換學(xué)習(xí),有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2023-07-07學(xué)習(xí) NodeJS 第八天:Socket 通訊實例
本篇文章主要介紹了學(xué)習(xí) NodeJS 第八天:Socket 通訊實例,非常具有實用價值,需要的朋友可以參考下。2016-12-12