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)
})

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

相关推荐
用户84913717547164 小时前
为什么 SNMP 叫"简单"?真相是:设备少干活,复杂全甩给了你
网络协议
白小飞不会飞5 小时前
【AUTOSAR】CP SOME/IP-TP
c++·嵌入式硬件·网络协议·车载系统·autosar
神一样的老师5 小时前
用 FCU1501 双网口打通两个不同网段:IP 转发 + NAT 实战
网络·网络协议·tcp/ip
晓得迷路了6 小时前
栗子前端技术周刊第 156 期 - jQuery 4.1、TanStack Query v6 路线图...
前端·javascript·node.js
keepquietl16 小时前
UDS on CAN 入门(6):诊断响应要等多久?读懂 P2、P2* 和 S3
网络·网络协议
YIAN1 天前
流式 TTS 和普通TTS到底有什么区别?一个文档教会你!
前端·websocket·node.js
郝学胜-神的一滴2 天前
Effective STL 条款12:对容器线程安全性的现实期望
c语言·开发语言·c++·qt·网络协议·rpc·numpy
光影少年2 天前
ts全栈开发
javascript·后端·typescript·node.js·c5全栈
FakeOccupational2 天前
fpga系列 HDL : 选择RAM IP(Two Port IP核) 乒乓缓冲(Ping-Pong Buffer)工作流程
网络协议·tcp/ip·fpga开发
爱和冰阔落2 天前
【Linux网络】GET 和 POST 真的只是参数位置不同吗?从 HTTP 请求方法、抓包分析到长连接与路由实战
linux·c++·http·网络编程·get与post