博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
浅度理解NodeJS的HTTP模块
阅读量:7229 次
发布时间:2019-06-29

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

HTTP模块是NodeJS自带的核心模块,其用法简单,只要创建一个服务器,然后监听端口,整个服务就跑起来啦

let http = require('http');let server = http.createServer(function(req,res){});server.listen(8080);复制代码

http模块createServer的callback中,

req(request)代表客户端的数据,是一个可读流;
res(response)代表服务端的数据,是一个可写流; 你可以拿到你想要的数据:

let http = require('http');let server = http.createServer();server.on('request', function (req, res) {    let buffers = [];    req.on('data', function (data) {        buffers.push(data);    });    req.on('end', function () {        console.log(Buffer.concat(buffers).toString());        res.write('hello node');        res.end();    });});复制代码

request事件是监听请求的事件,buffers是用来接收服务端发来的buffer数据,在end的时候console出来。res.write是可写流的write事件,往客户端写数据。当然,在这里我们并不能打印出来buffer因为还少一个请求头部,接下来,我们用代码模拟一下http模块的工作原理,让你一目了然。

服务端的代码和上段代码差不多,只是我们要接收到客户端的数据后用请求头部来判断数据的格式

let http = require('http');let queryString = require('querystring');let server = http.createServer();server.on('request', function (req, res) {    let contentType = req.headers['content-type'];    let buffers = [];    req.on('data', function (chunk) {        buffers.push(chunk);    });    req.on('end', function () {        let content = Buffer.concat(buffers).toString()        if(contentType === 'application/json'){            console.log(JSON.parse(content).name)        }else if(contentType === 'application/x-www-form-urlencoded'){            console.log(queryString.parse(content).name)        }        res.end('hello node');    });});server.listen(8080);复制代码

客户端我们把所有请求的头部信息整理成一个json然后用response事件拿到客户端的数据

let http = require('http');let options = {    hostname: 'localhost',    port: 8080,    path: '/',    method: 'get',    // 告诉服务端我当前要给你发什么样的数据    // headers: {     // json数据格式    //     'Content-Type': 'application/json',    //     'Content-Length': 16,     // 传输数据的长度(buffer的长度)    // },    headers:{         // 表单数据格式        'Content-Type':'application/x-www-form-urlencoded',        'Content-Length':16,    },}let req = http.request(options);req.on('response',function(res){    res.on('data',function(chunk){        console.log(chunk.toString());    });});// req.end('{"name":"haha"}');     // json数据格式req.end('name=haha&age=18');        // 表单数据格式复制代码

然后运行服务端文件

再用cmd切换到文件所在目录运行客户端文件

node httpClient.js  //客户端文件的名字复制代码

服务端会打出

{ name: 'haha', age: '18' }
客户端也会打出
hello node
怎么样~
经过这个小例子,是不是对http模块的理解更深了点呢

转载地址:http://tgdfm.baihongyu.com/

你可能感兴趣的文章
nginx启动脚本
查看>>
常用输入法框架简介
查看>>
记录新机房建设。20130629
查看>>
安装ntop
查看>>
ssh远程登录讲解
查看>>
mysql的备份脚本
查看>>
linux下mysql的root密码忘记解决方法
查看>>
7.索引的性能分析
查看>>
在 Delphi 下使用 DirectSound (17): 频率均衡效果器 IDirectSoundFXParamEq8
查看>>
文件操作命令一cp 2
查看>>
Multi-Mechanize工程目录结构说明
查看>>
halt
查看>>
标准ACL+扩展ACL+命名ACL
查看>>
Meteor应用的启动过程分析
查看>>
九曲黄河万里沙,浪淘风簸自天涯 — 正则表达式
查看>>
欲哭无泪,联想笔记本性价比
查看>>
很简单的在Ubuntu系统下安装字体和切换默认字体的方法
查看>>
我的友情链接
查看>>
dojo框架用hitch实现函数与上下文的绑定
查看>>
ubuntu编译安装vim7.4
查看>>