nodejs搭建web静态资源服务器
问题分析
由于我们无法事先得知一个.html文件中会引用多少个静态资源(.png, .css, .js....),所以,我们不能像处理某个页面一样去处理它们。
我们的解决办法是:
-
把所有的静态资源(.html,.png,.css,.js)全放在一个指定的目录里; 收到用户的请求之后,去指定的目录下去找对应的文件 找到,把内容读出来返回给用户。 找不到,报404。
1.准备文件
2.代码执行阶段
// 目标
// 完成server.js代码
// http://localhost:8088/index.html <----- public/index.html
// http://localhost:8088/style.css <----- public/style.css
// 1.引入模块
const http = require(http)
const path = require(path)
const fs = require(fs)
// 策略模式
const obj = {
".png": "image/png",
".jpg": "image/jpg",
".html": "text/html;charset=utf8",
".js": "application/javascript;charset=utf8",
".css": "text/css;charset=utf8"
}
// 2.创建服务
const server = http.createServer((req, res) => {
// 如果直接http://localhost:8088 ===> req.url 就是/ 这时希望去加载index.html
const url = req.url === / ? /index.html : req.url
// 如果 req.url 要访问的文件public里面找到 读出来 返回
const filePath = path.join(__dirname, public, url)
fs.readFile(filePath, function (err, data) {
if (err) {
res.statusCode = 404
res.send(not found)
} else {
// 获取后缀名
const extName = path.extname(filePath)
console.log(本次请求的资源, extName, filePath)
if (obj[extName]) {
res.setHeader(content-type, obj[extName])
}
res.end(data)
}
})
})
// 3.启用服务
server.listen(8099, () => {
console.log(跑起来了...)
})
3.在终端执行代码 让跑起来
4.在浏览器中查看
这样就可以查看我们当前访问的状态和看到帅气的冠希了!!!
