博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
node.js中使用http模块创建服务器和客户端
阅读量:6852 次
发布时间:2019-06-26

本文共 4612 字,大约阅读时间需要 15 分钟。

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

  

 

转载于:https://www.cnblogs.com/jkko123/p/10263465.html

你可能感兴趣的文章
ICMP协议
查看>>
ubuntu 编译php随笔
查看>>
mysql的存储结构
查看>>
[极客] - 如何优雅的吃水煮鸡蛋?
查看>>
在linux下安装配置svn独立服务器
查看>>
java基础教程-常用类(四)
查看>>
[Linux]Debian 9重启DNS重置问题
查看>>
struct2 学习之——可执行方法Action
查看>>
push、pop指令
查看>>
react-native热更新之CodePush详细介绍及使用方法
查看>>
CSS----reset.css 文件
查看>>
cookie笔记(二)
查看>>
深入理解Bootstrap-----读书笔记
查看>>
selenium 百度登录
查看>>
oracle:一台主机多个实例,sqlplus连接问题
查看>>
Windows python 3 安装OpenCV
查看>>
Dumb Bones UVA - 10529[多米诺重构]
查看>>
(5)U盘安装Linux系统
查看>>
HTML5标准学习 - 文档结构
查看>>
C语言strcat()函数:连接字符串
查看>>