第一步:准备工作
创建文件目录
- 文件夹分别来放对应后缀的文件index.css,index.html,index.js;并在index.html中导入, 不需要对写真实路径,src引入的路径在服务器上只是个代号
- server.js用来写服务器内部逻辑 是启动文件
了解node内置模块
-
fs模块:用来读取文件
fs.readFile(地址,格式,回调函数):读取指定地址文件按照指定格式显示,回调函数有(err,data)两个参数
-
http模块:执行http服务协议
http.createServer(function(req,res){//req为请求报文,//res为响应报文}):创建一个服务器
服务.listen(端口号,()=>{监听成功地回调}):监听服务器端口
-
正则表达式:
reg.exec('要匹配的数据'):如果成功返回数组[原数据,匹配数据]
第二步:实现功能
server.js写入
const http = require('http')
const fs = require('fs')
const server = http.createServer(function (req, res) {
const { url } = req
const reg = /^\/\w+\.(html|css|js)$/
const result = reg.exec(url)
if (result) {
fs.readFile('./' + result[1] + result[0], (err, data) => {
if (err) {
return console.log(err)
} else {
res.end(data)
}
})
}
}).listen('8080', () => { console.log('开启服务器') })
vscode命令行执行 node server 启动服务器
运行到浏览器并返回页面
返回页面成功