中山网站制作建设,html个人网站制作,皓丽智能会议平板官网,服务网站建设排行http模块是什么#xff1f; http 模块是 Node,js 官方提供的、用来创建 web 服务器的模块。通过 http 模块提供的 http.createServer() 方法#xff0c;就能方便的把一台普通的电脑#xff0c;变成一台Web 服务器#xff0c;从而对外提供 Web 资源服务。
如果我们想在node…http模块是什么 http 模块是 Node,js 官方提供的、用来创建 web 服务器的模块。通过 http 模块提供的 http.createServer() 方法就能方便的把一台普通的电脑变成一台Web 服务器从而对外提供 Web 资源服务。
如果我们想在node.js当中使用http模块需要做什么 我们需要导入http模块
const http require(http)使用http模块创建基础的web服务器
基本步骤 1.导http 模块 2.创建 web 服务器实例 3.为服务器实例绑定request 事件监听客户端的请求 4.启动服务器
// 1.导http 模块
const http require(http)
// 2.创建 web 服务器实例
const sever http.createSever()
// 3.为服务器实例绑定request 事件监听客户端的请求
// 使用on绑定事件有两个参数 绑定的事件 回调函数 第一个参数为request请求 第二个参数为response响应
sever.on(request,(request,response){console.log(1)
})
// 4.启动服务器
// 第一个参数是端口号 第二个参数是回调函数
sever.listen(80,(){console.log(2)
})我们在终端输出先输出2 然后我们去浏览器输入127.0.0.1 事件监听到了输出1
req请求对象
只要服务器接收到了客户端的请求就会调用通过 server.on() 为服务器绑定的 request 事件处理函数如果想在事件处理函数中访问与客户端相关的数据或属性可以使用如下的方式: req.ur1 是客户端请求的 URL 地址 req.method 是客户端的 method 请求类型
const http require(http)
const server http.createServer()
server.on(request,function(req,res){// 请求之后打印结果console.log(req.url) // 打印/console.log(req.method) // GET
})
server.listen(80,(){console.log(1)
})res响应对象
在服务器的 request 事件处理函数中如果想访问与服务器相关的数据或属性可以使用如下的方式:
const http require(http)
const server http.createServer()
server.on(request,function(req,res){const str 我是向客户端响应的内容// 向客户端发送指定的内容并结束这次请求的处理过程res.end(str)
})
server.listen(80,(){console.log(1)
})我们发现乱码了我们该如何处理
const http require(http)
const server http.createServer()
server.on(request,function(req,res){const str 我是向客户端响应的内容// 为了防止中文显示乱码的问题需要设置响应头 Content-Type 的值为 text/html; charsetutf-8res.setHeader(Content-Type,text/html;charsetutf-8)res.end(str)
})
server.listen(80,(){console.log(1)
})感谢大家的阅读如有不对的地方可以向我提出感谢大家