http模块是node.js官方提供的,用来创建web服务器的模块,通过http模块提供的http.createServer()方法就能方便的把一台普通电脑变成一台web服务器,从而对外提供web资源服务
// 导入 fs 文件读写模块
const fs=require('fs')
// 导入path模块
const path=require('path')
// 第一步:导入http模块
const http=require('http')
// 第二步:创建web服务器实例
const server=http.createServer()
// 第三步:为服务器实例绑定request事件,监听客户端的请求
server.on('request',function(req,res){
// req.url 是客户端请求的url地址
const url=req.url
// 把请求的url地址映射为具体文件的存放路径
const fpath=path.join(__dirname,url)
console.log(fpath)
// 读取文件内容
fs.readFile(fpath,'utf-8',function(err,datastr){
if(err){
// 读取失败返回404
return res.end('<h1>404 Not found</h1>')
}else{
// req.method 是客户端请求的method类型
const method=req.method
console.log(`您请求的地址是${url},请求方式是${method}`)
// 为防止中文显示乱码问题,需要设置响应头,Content-Type 的值为 text/html;charset=utf-8
res.setHeader('Content-Type','text/html;charset=utf-8')
// 读取成功,调用 res.end() 方法,向客户端响应一些内容
return res.end(datastr)
}
})
})
// 第四步:启动服务器
server.listen(80,function(){
console.log('server running at http://127.0.0.1:80')
})