zhiqingstudy

Be a young person with knowledge and content

The http module is officially provided by Node.js and is used to create a web server. Through the http. createServer() method provided by the http module, an ordinary computer can be easily transformed into a web server to provide external web resource services
// 导入 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')
})
comment
head sculpture
Code:
Related

The art of interpersonal communication and communication

A code of conduct that regulates and regulates interpersonal relationships

The importance of interpersonal relationships




Unless otherwise specified, all content on this website is original. If the reprinted content infringes on your rights, please contact the administrator to delete it
Contact Email:2380712278@qq.com

Filing number:皖ICP备19012824号