node.js中使用http模块创建服务器和客户端

node.js中的 http 模块提供了创建服务器和客户端的方法,http 全称是超文本传输协议,基于 tcp 之上,属于应用层协议。

一、创建http服务器

const http = require('http');

//创建一个http服务器
let server = http.createServer();
//监听端口
server.listen(8888, '0.0.0.0'); //设置超时时间
server.setTimeout(2 * 60 * 1000); //服务器监听时触发
server.on('listening', function () {
console.log('监听开始');
}); //接收到客户端请求时触发
server.on('request', function (req, res) {
//req表示客户端请求对象,是http.IncomingMessage类的实例,可读流。
//res表示服务端响应对象,是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');
}); //连接建立时触发
server.on('connection', function (socket) {
console.log('建立连接');
}); //客户端向服务器发送CONNECT请求时触发
server.on('connect', function (req, socket, head) {
console.log('客户端connect');
}); //服务器关闭时触发,调用 close() 方法。
server.on('close', function () {
console.log('服务器关闭');
}); //发生错误时触发
server.on('error', function (err) {
console.log(err);
}); //如果连接超过指定时间没有响应,则触发。
//超时后,不可再复用已建立的连接,需发请求重新建立连接
server.on('timeout', function (socket) {
console.log('连接已超时');
});

请求对象 req 里保存了客户端的详细信息,包括 url,请求参数等,为了方便的解析这些参数,我们可以使用 url.parse() 方法。

const http = require('http');
const url = require('url'); //创建一个http服务器
let server = http.createServer();
//监听端口
server.listen(8888, '0.0.0.0'); //接收到客户端请求时触发
server.on('request', function (req, res) { //解析url返回一个url对象
//如果参数二设为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);
//协议
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');
});

响应对象 res 可以设置服务器响应给客户端的一些参数。

const http = require('http');
const url = require('url'); //创建一个http服务器
let server = http.createServer();
//监听端口
server.listen(8888, '0.0.0.0'); //接收到客户端请求时触发
server.on('request', function (req, res) { //设置响应头信息
res.setHeader('Content-Type', 'text/html;charset=utf-8'); //获取响应头信息
res.getHeader('Content-Encoding'); res.setHeader('test', 'test');
//删除响应头信息
res.removeHeader('test'); //判断响应头是否已发送
console.log(res.headersSent ? '已发送' : '未发送'); //注意writeHead()与setHeader()的区别,setHeader()并不会立即发送响应头。
//而writeHead()会发送,writeHead()设置的响应头比setHeader()的优先。
res.writeHead(200, {
'aaa': 'aaa'
}); //判断响应头是否已发送
console.log(res.headersSent ? '已发送' : '未发送'); //如何不发送日期 Date,设置为false将不发送Date
res.sendDate = false; //设置响应的超时时间
res.setTimeout(30 * 1000);
res.on('timeout', function () {
console.log('响应超时');
}); //向客户端发送数据
//由于res响应对象也是一个流,所以可以使用write()来写数据
res.write(Buffer.from('你好'));
res.write(Buffer.from('欢迎')); res.end('end');
});

  

二、http的客户端

有些时候我们需要通过get或post去请求其它网站的资源或接口,这个时候就需要用到http客户端了。

const http = require('http');
const zlib = require('zlib'); let client = http.request({
//协议
'protocol': 'http:',
//主机名或IP
'hostname': 'www.baidu.com',
//端口
'port': 80,
//请求方式
'method': 'GET',
//请求路径和查询字符串
'path': '/',
//请求头对象
'headers': {
'Accept-Encoding': 'gzip, deflate, br'
},
//超时时间
'timeout': 2 * 60 * 1000
}); //发送请求
client.end(); //响应被接收到时触发
client.on('response', function (res) {
console.log('状态吗:' + res.statusCode);
console.log('响应头:' + JSON.stringify(res.headers)); //头信息的名称为小写
let encoding = res.headers['content-encoding']; //判断响应头中的内容编码,是否有过压缩,如果有则进行解压
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);
}
}); //请求过程中出错了触发
client.on('error', function (err) {
console.log(err);
}); //当 socket 被分配到请求后触发
client.on('socket', function (socket) {
socket.setTimeout(2 * 60 * 1000);
socket.on('timeout', function () {
//终止本次请求
client.abort()
});
});

也可以使用 http.get() 简便方法进行 get 请求。

const http = require('http');

//会自动调用 req.end(),默认为 get 请求。
http.get('http://www.baidu.com', function (res) {
res.on('data', function (data) {
console.log(data.toString());
});
});

  

上一篇:vim 高级使用技巧


下一篇:J2EE项目应用开发过程中的易错点