Node.js之http模块

http模块是什么?

http 模块是 Node,js 官方提供的、用来创建 web 服务器的模块。通过 http 模块提供的 http.createServer() 方法,就能方便的把一台普通的电脑,变成一台Web 服务器,从而对外提供 Web 资源服务。

如果我们想在node.js当中使用http模块需要做什么?

我们需要导入http模块

javascript 复制代码
const http = require("http")

使用http模块创建基础的web服务器

基本步骤

1.导http 模块

2.创建 web 服务器实例

3.为服务器实例绑定request 事件,监听客户端的请求

4.启动服务器

javascript 复制代码
// 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 请求类型

javascript 复制代码
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 事件处理函数中,如果想访问与服务器相关的数据或属性,可以使用如下的方式:

javascript 复制代码
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)
})


我们发现乱码了,我们该如何处理?

javascript 复制代码
const http = require("http")
const server = http.createServer()
server.on("request",function(req,res){
    const str = "我是向客户端响应的内容"
    // 为了防止中文显示乱码的问题,需要设置响应头 Content-Type 的值为 text/html;  charset=utf-8
    res.setHeader("Content-Type","text/html;charset=utf-8")
    res.end(str)
})
server.listen(80,()=>{
    console.log(1)
})

感谢大家的阅读,如有不对的地方,可以向我提出,感谢大家!

相关推荐
笑醉踏歌行2 小时前
NVM,Node.Js 管理工具
运维·ubuntu·node.js
酷爱码3 小时前
在 Linux 中修改 Apache HTTP Server(httpd)默认端口的完整指南
linux·http·apache
程序员祥云3 小时前
https相比http的区别
网络协议·http·https
熙客4 小时前
应用层协议:HTTPS
网络协议·https
chxii4 小时前
1.4 Node.js 的 TCP 和 UDP
node.js
小吕学编程5 小时前
HttpServletRequest常用方法
java·http
2501_915106326 小时前
Flutter、React Native 项目如何搞定 iOS 上架?从构建 IPA 到上传 App Store 的实战流程全解析
websocket·网络协议·tcp/ip·http·网络安全·https·udp
snetlogon207 小时前
JDK17 Http Request 异步处理 源码刨析
android·网络协议·http
还有几根头发呀10 小时前
UDP 与 TCP 调用接口的差异:面试高频问题解析与实战总结
网络·网络协议·tcp/ip·面试·udp
秋水丶秋水11 小时前
SSL安全证书怎么安装?
网络协议·http·https