Nodejs核心模块之net和http的使用详解

2020-06-17 06:37:26易采站长站整理

} 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);
})