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模块的理解更深了点呢