node.js使用http模块创建服务器和客户端完整示例

2020-06-17 07:56:46易采站长站整理

//协议
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);