1、先实现在url中输入文件路径能展示对应文件内容功能
const http = require('http') const fs = require('fs') const server = http.createServer() const wwwDir = '/Users/lianglanlan/Desktop/code/study/node/www' server.on('request', (req, res) => { const url = req.url let filePath = '/index.html' if (url !== '/') { filePath = url } fs.readFile(wwwDir + filePath, (err, data) => { if (err) { console.log(err) return res.end('404 Not Found') } res.end(data) }) }) server.listen(3010, () => { console.log('running...') })
2、展示页面template.html
用谷歌浏览器打开文件夹,复制整个html,删除无用js
简单写出这样的html页面
3、修改requset事件中url对应的展示页面为template.html
server.on('request', (req, res) => { fs.readFile('./template.html', (err, data) => { if (err) { return res.end('404 Not Found') } res.end(data) }) })