[node] 4 http模块
前言
http模块是Node中一个重要的方法,让前端开发者可以本地起服务。
目标
1 了解什么是服务器
2 掌握http模块的用法
服务器相关
1 服务器
在网络节点中,负责消费资源的电脑叫做客户端;
负责对外提供网络资源的电脑,叫做服务器。
1.1 IP地址
Ip地址是互联网上每台计算机的唯一地址,具有唯一性。相当于手机电话号码,只有知道Ip地址才能进行通信。
在cmd终端中,用ping可以获取域名对应的的IP地址
ping 域名地址
普通电脑与服务器的区别
在普通电脑上安装服务器软件,如IIS、Apache等,就可以把普通电脑变成一台web服务器。
1.2 域名与服务器
域名是与Ip地址一一对应的,但是因为Ip地址不便于记忆,才有了域名。
域名与Ip的对应关系存放在域名服务器中(DNS)
域名服务器就是提供IP地址和域名之间转换服务的服务器
http相关
2 http模块
http 模块是Node.js官方提供的,用来创建web 服务器的模块。通过http模块提供的createServer()方法,就能方便的把一台普通的电脑,变成一台服务器,从而对外提供web 资源服务。
2.1 http模块使用步骤
1 引入http模块
const http = require(`http`)
2 创建http实例
const server = http.createServer();
3 为服务器实例绑定 request 时间,监听客户端的请求
server.on('request',function (req,res){
console.log('--------req,res--------',req,res)
})
4 启动服务器
server.listen(8080,function(){
console.log('Localhost http://127.0.0.1')
})
5 执行index.js
2.2 中文乱码
server.on('request',function (req,res){
const str = `你访问的 url 地址是${req.url},请求的 method 类型是${req.method}`
// 设置Content-Type请求头,解决中文乱码
res.setHeader('Content-Type', 'text/html;charset=utf-8')
// 将内容响应给客户端
res.end(str)
})
完整代码
// 导入http模块
const http = require('http');
// 创建http实例
const server = http.createServer();
// 为服务器实例绑定 request 时间,监听客户端的请求
server.on('request',function (req,res){
const str = `你访问的 url 地址是${req.url},请求的 method 类型是${req.method}`
// 设置Content-Type请求头,解决中文乱码
res.setHeader('Content-Type', 'text/html;charset=utf-8')
// 将内容响应给客户端
res.end(str)
})
// 启动服务器
server.listen(8080,function(){
console.log('Localhost http://127.0.0.1')
})
2.3 响应不同内容
server.on('request',function (req,res){
const str = `你访问的 url 地址是${req.url},请求的 method 类型是${req.method}`
console.log('----------',req.url)
// 要相应的内容
let content = `<h1>404 NOT FOUND</h1>`
// 根据不同路径返回不同内容
if(req.url=='/'|| req.url=='/index.html'){
content = `<h1>欢迎进入首页</h1>`
}else if(req.url == '/screen.html'){
content = `<h1>欢迎使用大屏</h1>`
}
// 设置Content-Type请求头,解决中文乱码
res.setHeader('Content-Type', 'text/html;charset=utf-8')
// 将内容响应给客户端
res.end(content)
})