Nodejs核心模塊之net和http的使用詳解
前言
net和http模塊都是node核心模塊之一,他們都可以搭建自己的服務(wù)端和客戶(hù)端,以響應(yīng)請(qǐng)求和發(fā)送請(qǐng)求。
net模塊服務(wù)端/客戶(hù)端
這里寫(xiě)的net模塊是基于tcp協(xié)議的服務(wù)端和客戶(hù)端,用到net.createServer和net.connect實(shí)現(xiàn)的一個(gè)簡(jiǎn)單請(qǐng)求與響應(yīng)的demo。
//tcp服務(wù)端 var net = require('net') var sever=net.createServer(function(connection){ //客戶(hù)端關(guān)閉連接執(zhí)行的事件 connection.on('end',function(){ // console.log('客戶(hù)端關(guān)閉連接') }) connection.on('data',function(data){ console.log('服務(wù)端:收到客戶(hù)端發(fā)送數(shù)據(jù)為'+data.toString()) }) //給客戶(hù)端響應(yīng)的數(shù)據(jù) connection.write('response hello') }) sever.listen(8080,function(){ // console.log('監(jiān)聽(tīng)端口') })
//tcp客戶(hù)端 var net = require('net') var client = net.connect({port:8080},function(){ // console.log("連接到服務(wù)器") }) //客戶(hù)端收到服務(wù)端執(zhí)行的事件 client.on('data',function(data){ console.log('客戶(hù)端:收到服務(wù)端響應(yīng)數(shù)據(jù)為'+data.toString()) client.end() }) //給服務(wù)端傳遞的數(shù)據(jù) client.write('hello') client.on('end',function(){ // console.log('斷開(kāi)與服務(wù)器的連接') })
運(yùn)行結(jié)果
http模塊四種請(qǐng)求類(lèi)型
http服務(wù)端:
http.createServer創(chuàng)建了一個(gè)http.Server實(shí)例,將一個(gè)函數(shù)作為HTTP請(qǐng)求處理函數(shù)。這個(gè)函數(shù)接受兩個(gè)參數(shù),分別是請(qǐng)求對(duì)象(req)處理請(qǐng)求的一些信息和響應(yīng)對(duì)象(res)處理響應(yīng)的數(shù)據(jù)。
//http服務(wù)端 const http = require("http"); var fs = require("fs"); var url = require('url') http.createServer(function (req, res) { var urlPath = url.parse(req.url); var meth = req.method //urlPath.pathname 獲取及設(shè)置URL的路徑(path)部分 //meth 獲取請(qǐng)求數(shù)據(jù)的方法,一個(gè)路徑只能被一種方法請(qǐng)求,其他方法請(qǐng)求時(shí)返回404 if (urlPath.pathname === '/' && meth === 'GET') { res.write(' get ok'); } else if (urlPath.pathname === '/users' && meth === 'POST') { res.writeHead(200, { 'content-type': 'text/html;charset=utf-8' }); fs.readFile('user.json', function (err, data) { if (err) { return console.error(err); } var data = data.toString(); // 返回?cái)?shù)據(jù) res.write(data); }); } else if (urlPath.pathname === '/list' && meth === 'PUT') { res.write('put ok'); } else if (urlPath.pathname === '/detail' && meth === 'DELETE') { res.write(' delete ok'); } else { res.writeHead(404, { 'content-type': 'text/html;charset=utf-8' }); res.write('404') } res.on('data', function (data) { console.log(data.toString()) }) }).listen(3000, function () { console.log("server start 3000"); });
http客戶(hù)端:
http模塊提供了兩個(gè)創(chuàng)建HTTP客戶(hù)端的方法http.request和http.get,以向HTTP服務(wù)器發(fā)起請(qǐng)求。http.get是http.request快捷方法,該方法僅支持GET方式的請(qǐng)求。
http.request(options,callback)方法發(fā)起http請(qǐng)求,option是請(qǐng)求的的參數(shù),callback是請(qǐng)求的回掉函數(shù),在請(qǐng)求被響應(yīng)后執(zhí)行,它傳遞一個(gè)參數(shù),為http.ClientResponse的實(shí)例,處理返回的數(shù)據(jù)。
options常用的參數(shù)如下:
1)host:請(qǐng)求網(wǎng)站的域名或IP地址。
2)port:請(qǐng)求網(wǎng)站的端口,默認(rèn)80。
3)method:請(qǐng)求方法,默認(rèn)是GET。
4)path:請(qǐng)求的相對(duì)于根的路徑,默認(rèn)是“/”。請(qǐng)求參數(shù)應(yīng)該包含在其中。
5)headers:請(qǐng)求頭的內(nèi)容。
nodejs實(shí)現(xiàn)的爬蟲(chóng)其實(shí)就可以用http模塊創(chuàng)建的客戶(hù)端向我們要抓取數(shù)據(jù)的地址發(fā)起請(qǐng)求,并拿到響應(yīng)的數(shù)據(jù)進(jìn)行解析。
get
//http客戶(hù)端 const http = require("http"); // 發(fā)送請(qǐng)求的配置 let config = { host: "localhost", port: 3000, path:'/', method: "GET", headers: { a: 1 } }; // 創(chuàng)建客戶(hù)端 let client = http.request(config, function(res) { // 接收服務(wù)端返回的數(shù)據(jù) let repData=''; res.on("data", function(data) { repData=data.toString() console.log(repData) }); res.on("end", function() { // console.log(Buffer.concat(arr).toString()); }); }); // 發(fā)送請(qǐng)求 client.end();結(jié)束請(qǐng)求,否則服務(wù)器將不會(huì)收到信息
客戶(hù)端發(fā)起http請(qǐng)求,請(qǐng)求方法為get,服務(wù)端收到get請(qǐng)求,匹配路徑是首頁(yè),響應(yīng)數(shù)據(jù):get ok。
post
//http客戶(hù)端 var http = require('http'); var querystring = require("querystring"); var contents = querystring.stringify({ name: "艾利斯提", email: "m778941332@163.com", address: " chengdu", }); var options = { host: "localhost", port: 3000, path:"/users", method: "POST", headers: { "Content-Type": "application/x-www-form-urlencoded", "Content-Length": contents.length } }; var req = http.request(options, function (res) { res.setEncoding("utf8"); res.on("data", function (data) { console.log(data); }) }) req.write(contents); //結(jié)束請(qǐng)求,否則服務(wù)器將不會(huì)收到信息 req.end(); //響應(yīng)的數(shù)據(jù)為 { "user1" : { "name" : "mahesh", "password" : "password1", "profession" : "teacher", "id": 1 }, "user2" : { "name" : "suresh", "password" : "password2", "profession" : "librarian", "id": 2 } }
客戶(hù)端發(fā)起http請(qǐng)求,請(qǐng)求方法為post,post傳遞數(shù)據(jù),匹配路徑是/users,服務(wù)器響應(yīng)請(qǐng)求并返回?cái)?shù)據(jù)user.json里的內(nèi)容。
put
//http客戶(hù)端 const http = require("http"); // 發(fā)送請(qǐng)求的配置 let config = { host: "localhost", port: 3000, path:"/list", method: "put", headers: { a: 1 } }; // 創(chuàng)建客戶(hù)端 let client = http.request(config, function(res) { // 接收服務(wù)端返回的數(shù)據(jù) let repData=''; res.on("data", function(data) { repData=data.toString() console.log(repData) }); res.on("end", function() { // console.log(Buffer.concat(arr).toString()); }); }); // 發(fā)送請(qǐng)求 client.end();
客戶(hù)端發(fā)起http請(qǐng)求,請(qǐng)求方法為put,服務(wù)端收到put請(qǐng)求,匹配路徑為/list,響應(yīng)數(shù)據(jù):put ok
delect
//http delete請(qǐng)求客戶(hù)端 var http = require('http'); var querystring = require("querystring"); var contents = querystring.stringify({ name: "艾利斯提", email: "m778941332@163.com", address: " chengdu", }); var options = { host: "localhost", port: 3000, path:'/detail', method: "DELETE", headers: { "Content-Type": "application/x-www-form-urlencoded", "Content-Length": contents.length } }; var req = http.request(options, function (res) { res.setEncoding("utf8"); res.on("data", function (data) { console.log(data); }) }) req.write(contents); req.end();
服務(wù)端收到delete請(qǐng)求,匹配路徑為/detail,響應(yīng)數(shù)據(jù):delete ok
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
nodejs讀寫(xiě)json文件的簡(jiǎn)單方法(必看)
下面小編就為大家?guī)?lái)一篇nodejs讀寫(xiě)json文件的簡(jiǎn)單方法(必看)。2017-03-03解決Node.js使用MySQL出現(xiàn)connect ECONNREFUSED 127.0.0.1:3306的問(wèn)題
這篇文章主要介紹了解決Node.js使用MySQL出現(xiàn)connect ECONNREFUSED 127.0.0.1:3306報(bào)錯(cuò)的相關(guān)資料,文中將問(wèn)題描述的很清楚,解決的方法也介紹的很完整,需要的朋友可以參考借鑒,下面來(lái)一起看看吧。2017-03-03NodeJS學(xué)習(xí)筆記之Module的簡(jiǎn)介
模塊是Node.js 應(yīng)用程序的基本組成部分,文件和模塊是一一對(duì)應(yīng)的。換言之,一個(gè) Node.js 文件就是一個(gè)模塊,這個(gè)文件可能是JavaScript 代碼、JSON 或者編譯過(guò)的C/C++ 擴(kuò)展。2017-03-03Node.js中child_process實(shí)現(xiàn)多進(jìn)程
這篇文章主要介紹了Node.js中child_process實(shí)現(xiàn)多進(jìn)程,需要的朋友可以參考下2015-02-02從零學(xué)習(xí)node.js之簡(jiǎn)易的網(wǎng)絡(luò)爬蟲(chóng)(四)
簡(jiǎn)單的爬蟲(chóng)實(shí)現(xiàn)原理很簡(jiǎn)單:發(fā)送http請(qǐng)求至目標(biāo)地址獲取HTML頁(yè)面數(shù)據(jù),然后從獲取來(lái)的頁(yè)面數(shù)據(jù)中提取需要的數(shù)據(jù)保存。下面這篇文章主要介紹了利用node.js實(shí)現(xiàn)簡(jiǎn)易的網(wǎng)絡(luò)爬蟲(chóng)的相關(guān)資料,需要的朋友可以參考下。2017-02-02node-gyp安裝vuetify編譯失敗gyp?ERR的問(wèn)題及解決
這篇文章主要介紹了node-gyp安裝vuetify編譯失敗gyp?ERR的問(wèn)題及解決方案,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-03-03Nodejs小文件拷貝復(fù)制和大文件拷貝復(fù)制方法代碼
NodeJS提供了基本的文件操作API,但是像文件拷貝復(fù)制這種高級(jí)功能就沒(méi)有提供,因此我們先拿文件拷貝程序練手,文件拷貝復(fù)制是在Node.js中常見(jiàn)的操作之一,它允許我們將一個(gè)文件的內(nèi)容復(fù)制到另一個(gè)文件中2023-11-11