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')
})
评论
头像
验证码:
相关推荐

七年之痒是什么意思

520送什么给女友

第一次见女方父母送什么好




如果未经特殊说明,本站内容皆为原创,转载内容如果侵犯了您的权益,如有侵权请联系管理员删除
联系QQ:2380712278

备案号:皖ICP备19012824号