客户端&服务器
回顾ajax中关于客户端和服务器的介绍
在网络节点中,负责消费资源的电脑,叫做客户端
负责对外提供网络资源的电脑,叫做服务器
http模块简介
由nodejs官方提供、用来创建Web服务器的模块。通过http模块提供的http.createServer() 方法,就能方便的把一台普通的电脑,变成一台Web服务器,从而对外提供Web资源服务。
使用前需要导入:
const http=require('http')
进一步理解http模块
服务器和普通电脑的区别在于,服务器上安装了web服务器软件,例如IIS(ASP技术领域),Apache(PHP技术领域)等。通过安装这些软件,就能把一台普通的电脑变成一台web服务器。
在node中,我们不需要使用IIS、Apache等这些第三方web服务器软件。因为我们可以基于Node.js提供的http模块,通过几行简单的代码,就能轻松的手写一个服务器软件,从而对外提供web服务
创建最基本的web服务器
1.导入http模块
const http=require('http')
2.创建web服务器实例
调用http.creatServer()方法,即可快速创建一个web服务器实例:
const server=http.creatServer()
3.为服务器实例绑定request事件,监听客户端的请求
server.on('request',(req,res)=>{
console.log('Someone visit our web server')
})
4.启动服务器
调用服务器实例的.listen()方法,即可启动当前的web服务器实例
server.listen(80,()=>{
console.log('http server running at http://127.0.0.1')
})
req请求对象
只要服务器接受了客户端的请求,就会调用server.on()为服务器绑定的request事件处理函数。
可以在事件处理函数中,访问客户端相关的数据或属性
例如 req.url、req.method等
res响应对象
在服务器的request事件处理函数中,访问与服务器相关的数据或属性
res.end() 向客户端发送指定的内容,并结束这次请求的处理过程。
server.on('request',(req,res)=>{
const str='your request url is '+req.url+',and request method is '+req.method+'}'
console.log(str)
res.end(str)
})
解决中文乱码问题
需要手动设置内容的编码格式!
为了防止中文显示乱码的问题,需要设置响应头 Content-Type的值为 text/html;charset=utf-8
res.setHeader('Content-Type','text/html;charset=utf-8')
根据不同的url相应不同的html内容
1.获取请求的url地址
2.设置默认的相应内容为404 Not found
3.判断用户请求的是否为/或/index.html首页
4.判断用户请求的是否为/about.html关于页面
5.设置Content-Type响应头,防止中文乱码
6.使用res.end()把内容相应给客户端
// 导入模块
const http=require('http')
// web服务器实例
const server=http.createServer()
// 绑定request事件
server.on('request',(req,res)=>{
const url=req.url //拿到客户端请求的url
let content ='<h1>404 NOT FOUND !!!</h1>' //设置未找到页面的提示信息
if(['/','/index.html'].includes(url)){ //判断用户请求的是否为/或/index.html首页
content='<h1>success1</h1>'
}else if(url==='/about.html'){ //判断用户请求的是否为/about.html关于页面
content='<h1>success1</h1>'
}
res.setHeader('Content-Type','text/html;charset=utf-8') //设置Content-Type响应头,防止中文乱码
res.end(content) //使用res.end()把内容相应给客户端
})
server.listen('80',function(){
console.log('Server running at http://127.0.0.1')
})
实际应用中,请求的url应当与服务器的文件路径相同,所以一般需要再做一层映射:
const url=req.url
const fpath=path。join(__dirname,url)