基于 Web 服务,开发提供网页资源的功能,了解下后端的代码工作过程
步骤:
- 基于 http 模块,创建 Web 服务
- 使用 req.url 获取请求资源路径为 /index.html 的时候,读取 index.html 文件内容字符串返回给请求方
- 其他路径,暂时返回不存在的提示
- 运行 Web 服务,用浏览器发起请求
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
|
const fs = require('fs') const path = require('path')
const http = require('http') const server = http.createServer() server.on('request', (req, res) => { if (req.url === '/index.html') { fs.readFile(path.join(__dirname, 'dist/index.html'), (err, data) => { res.setHeader('Content-Type', 'text/html;charset=utf-8') res.end(data.toString()) }) } else { res.setHeader('Content-Type', 'text/html;charset=utf-8') res.end('你要访问的资源路径不存在') } }) server.listen(8080, () => { console.log('Web 服务启动了') })
|