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 中国大陆许可协议进行许可。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步