http、http2模块都是node.js的核心模块,下面分别对这些模块进行分析。
使用http模块只需要在文件中通过require(“http”) 引入即可。http模块是node.js原生的中最为亮眼的模块。传统的HTTP服务器都会由nginx之类的软件来担任,但是node.js不需要。node.js的http模块本身就可以构建服务器,而且性能非常可靠。
1、Node.js服务端
下面创建一个简单的NOde.js服务器。
const http = require("http")
const server = http.createServer(function(req,res){res.writeHead(200,{"content-type":"text/plain"})res.end("hello,Node.js!")
})server.listen(3000,function(){console.log("listening port 3000!")
})
运行这段代码,在浏览器打开http://localhost:3000/ 页面中就会显示“Hello Node.js!”文字
http.createServer()方法返回的是http模板封装的一个基于时间的http服务器。同样,http.request是封装的一个http客户端工具,可以用来向http服务器发起请求。上面的req和res分别是http.IncomingMessage和http.ServerResponse的实例。
http.Server的事件主要有:
http.createServer()方法其实就是添加了一个request事件监听,利用下面的代码同样可以实现效果。
const http = require("http")
const server = new http.Server();server.on('request', function (req, res) {res.writeHead(200, {"content-type": "text/plain"})res.end("hello,Node.js!")
})server.listen(3000, function () {console.log("listening port 3000!")
})
http.IncomingMessage是http请求的信息,提供了以下三个事件:
http.IncomingMessage提供的属性主要有:
const http = require("http")const server = http.createServer(function (req, res) {let data = ""req.on('data', function (chunk) {data += chunk;})req.on("end", function () {let method = req.method;let url = req.url;let headers = JSON.stringify(req.headers);let httpVersion = req.httpVersion;res.writeHead(200, {"content-type": "text/html"});let dataHtml = `data:` + data + `
`let urlHtml = `url:` + url + `
`let methodHtml = `method:` + method + `
`let resdata = dataHtml + urlHtml + methodHtmlres.end(resdata)})
})server.listen(3000, function () {console.log("listening port 3000!")
})
http.ServerResponse 是返回给客户端的信息,其常用的方法为:
这些方法在上面的代码中已经演示过了,这里就不再演示了。
2、客户端向http服务器发送请求
以上方法都是http模块在服务器端的使用,接下来看客户端的使用。向http服务器发起请求的方法有:
const http = require("http")
let reqData = ""
http.request({'host': '127.0.0.1','port': '3000','method': 'get'
}, function (res) {res.on('data', function (chunk) {reqData += chunk;})res.on('end', function () {console.log(reqData)})})