Nodejs核心模組之net和http

半截的詩發表於2019-03-29

前言

net和http模組都是node核心模組之一,他們都可以搭建自己的服務端和客戶端,以響應請求和傳送請求。

net模組服務端/客戶端

這裡寫的net模組是基於tcp協議的服務端和客戶端,用到net.createServer和net.connect實現的一個簡單請求與響應的demo。

//tcp服務端
var net = require('net')
var sever=net.createServer(function(connection){
    //客戶端關閉連線執行的事件
  connection.on('end',function(){
    //   console.log('客戶端關閉連線')
  })
  connection.on('data',function(data){
    console.log('服務端:收到客戶端傳送資料為'+data.toString())
})
//給客戶端響應的資料
  connection.write('response hello')
})
sever.listen(8080,function(){
    // console.log('監聽埠')
})

複製程式碼
//tcp客戶端
var net = require('net')
var client = net.connect({port:8080},function(){
    // console.log("連線到伺服器")
})
//客戶端收到服務端執行的事件
client.on('data',function(data){
    console.log('客戶端:收到服務端響應資料為'+data.toString())
    client.end()
})
//給服務端傳遞的資料
client.write('hello')
client.on('end',function(){
    // console.log('斷開與伺服器的連線')
})
複製程式碼

執行結果

Nodejs核心模組之net和http
Nodejs核心模組之net和http

http模組四種請求型別

http服務端:

http.createServer建立了一個http.Server例項,將一個函式作為HTTP請求處理函式。這個函式接受兩個引數,分別是請求物件(req)處理請求的一些資訊和響應物件(res)處理響應的資料。

//http服務端
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 獲取及設定URL的路徑(path)部分
    //meth 獲取請求資料的方法,一個路徑只能被一種方法請求,其他方法請求時返回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();
            // 返回資料
            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客戶端:

http模組提供了兩個建立HTTP客戶端的方法http.request和http.get,以向HTTP伺服器發起請求。http.get是http.request快捷方法,該方法僅支援GET方式的請求。

http.request(options,callback)方法發起http請求,option是請求的的引數,callback是請求的回掉函式,在請求被響應後執行,它傳遞一個引數,為http.ClientResponse的例項,處理返回的資料。
options常用的引數如下: 1)host:請求網站的域名或IP地址。
2)port:請求網站的埠,預設80。
3)method:請求方法,預設是GET。
4)path:請求的相對於根的路徑,預設是“/”。請求引數應該包含在其中。
5)headers:請求頭的內容。

nodejs實現的爬蟲其實就可以用http模組建立的客戶端向我們要抓取資料的地址發起請求,並拿到響應的資料進行解析。

get

//http客戶端
const http = require("http");
// 傳送請求的配置
let config = {
    host: "localhost",
    port: 3000,
    path:'/',
    method: "GET",
    headers: {
        a: 1
    }
};
// 建立客戶端
let client = http.request(config, function(res) {
    // 接收服務端返回的資料
   let repData='';
    res.on("data", function(data) {
        repData=data.toString()
        console.log(repData)
    });
    res.on("end", function() {
        // console.log(Buffer.concat(arr).toString());
    });
});
// 傳送請求
client.end();結束請求,否則伺服器將不會收到資訊

複製程式碼

客戶端發起http請求,請求方法為get,服務端收到get請求,匹配路徑是首頁,響應資料:get ok。

post

//http客戶端
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);
//結束請求,否則伺服器將不會收到資訊
req.end(); 
//響應的資料為
{
    "user1" : {
       "name" : "mahesh",
       "password" : "password1",
       "profession" : "teacher",
       "id": 1
    },
    "user2" : {
       "name" : "suresh",
       "password" : "password2",
       "profession" : "librarian",
       "id": 2
    }
 }
複製程式碼

客戶端發起http請求,請求方法為post,post傳遞資料,匹配路徑是/users,伺服器響應請求並返回資料user.json裡的內容。

put

//http客戶端
const http = require("http");
// 傳送請求的配置
let config = {
    host: "localhost",
    port: 3000,
    path:"/list",
    method: "put",
    headers: {
        a: 1
    }
};
// 建立客戶端
let client = http.request(config, function(res) {
    // 接收服務端返回的資料
   let repData='';
    res.on("data", function(data) {
        repData=data.toString()
        console.log(repData)
    });
    res.on("end", function() {
        // console.log(Buffer.concat(arr).toString());
    });
});
// 傳送請求
client.end();
複製程式碼

客戶端發起http請求,請求方法為put,服務端收到put請求,匹配路徑為/list,響應資料:put ok

delect

//http delete請求客戶端
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();
複製程式碼

服務端收到delete請求,匹配路徑為/detail,響應資料:delete ok

相關文章