node04_05时钟web服务器

1.创建clock文件夹,里面有index.hrml和对应的css文件

 

 2.编写node代码

//1.1导入http模块
const http = require('http')
//1.2导入fs模块
const fs = require('fs')
//1.3导入path模块
const path = require('path')
//2.1创建web服务器
const server = http.createServer()
//2.2监听web服务器的request事件
server.on('request', function (req, res) {
    //3.1获取到客户端请求的URL地址
    const url = req.url
    // /clock/index.html
    // /clock/index.css 
    // /clock/index.js

    //3.2把请求的URL地址映射为具体的文件存放路径
    // const fpath = path.join(__dirname,url)
    // console.log(fpath)
    //5.优化资源的请求路径
    //5.1预定义空白文件存放路径
    let fpath = ''
    if (req.url === '/') {
        fpath = path.join(__dirname, '/clock/index.html')
        console.log(fpath)
    } else {
        //    /index.html
        //   /index.css 
        //  /index.js

        fpath = path.join(__dirname, '/clock', url)
        console.log(fpath)
    }
    //4.1根据'映射'过来的文件路径来读取文件内容
    fs.readFile(fpath, 'utf-8', (err, dataStr) => {
        if (err) {
            //4.2读取失败向客户端返回固定的错误信息
            return res.end('404 not found')
        }
        res.end(dataStr)
        //4.3读取成功将读取成功的内容响应给客户端
    })

})
//2.3启动服务器
server.listen(80, () => {
    console.log('Server running at http://127.0.0.1')
})

 这里相当于托管一个静态资源,简单的演示了服务端是怎么进行html文件的展示的。

posted @ 2022-11-01 13:45  SadicZhou  阅读(17)  评论(0编辑  收藏  举报