Node.js核心模块net与http概述
前言
net与http均为Node.js的核心内置模块,二者均具备构建服务端与客户端的能力,能够处理请求接收与发送操作。
net模块的服务端与客户端实现
本节介绍的net模块示例基于TCP协议,利用net.createServer建立服务端,配合net.connect建立客户端,从而完成一个基础的数据请求与响应演示。
//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('断开与服务器的连接')
})
运行结果展示


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.request和http.get两种方法来创建HTTP客户端并向服务器发起请求。其中http.get是http.request的便捷封装,仅支持GET方式的请求。
http.request(options, callback)用于发起HTTP请求。options参数包含请求配置,callback为回调函数,在请求获得响应后执行,其参数为http.ClientResponse实例,用于处理返回数据。
options参数常用配置如下:
1)host:指定目标网站的域名或IP地址。 2)port:指定目标网站端口,默认为80。 3)method:指定请求方法,默认为GET。 4)path:指定相对于根目录的路径,默认为“/”,查询参数应包含在此处。 5)headers:设置请求头内容。
Node.js实现的网络爬虫通常利用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();结束请求,否则服务器将不会收到信息
客户端发起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
}
}
客户端发起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();
客户端发起PUT请求,服务端匹配路径为/list,并响应数据“put ok”。
DELETE请求示例
//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”。
以上内容涵盖了net和http模块的基础应用,希望对读者学习有所帮助,欢迎继续支持本站。