灵心如玉,守一生无惧|

SadicZhou

园龄:3年2个月粉丝:7关注:4

node04_05时钟web服务器

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

 

 2.编写node代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
//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文件的展示的。

本文作者:SadicZhou

本文链接:https://www.cnblogs.com/SadicZhou/p/16847397.html

版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。

posted @   SadicZhou  阅读(19)  评论(0编辑  收藏  举报
点击右上角即可分享
微信分享提示
评论
收藏
关注
推荐
深色
回顶
收起
  1. 1 尚好的青春 孙燕姿
  2. 2 孙燕姿
  3. 3 克卜勒 孙燕姿
- 孙燕姿
00:00 / 00:00
An audio error has occurred, player will skip forward in 2 seconds.