问题分析
由于我们无法事先得知一个.html文件中会引用多少个静态资源(.png, .css, .js....),所以,我们不能像处理某个页面一样去处理它们。
我们的解决办法是:
-
把所有的静态资源(.html,.png,.css,.js)全放在一个指定的目录里;
-
收到用户的请求之后,去指定的目录下去找对应的文件
-
找到,把内容读出来返回给用户。
-
找不到,报404。
-
目录如下:
|-public
|-public/index.html
|-public/stye.css
|-public/1.png
|-server.js
在上面的目录结构中,我们把所有的静态资源全放在public下面,然后使用server.js来启动web服务器。
代码
// 1. 引入http、path、fs模块
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(function (req, res) {
console.log("有人访问了");
// 如果直接在地址栏写 http://localhost:8085 ===> 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, (err, data) => {
if (err) {
res.statusCode = 404;
res.end("not found");
} else {
// 获取后缀名
const extName = path.extname(filePath);
if (obj[extName]) {
res.setHeader("content-type", obj[extName]);
}
res.end(data);
}
});
});
// 3. 启动服务
server.listen(8084, function () {
console.log("服务器启动成功,请在http://localhost:8084中访问....");
});
写完代码之后在当前文件夹地址栏打开cmd
之后输入node server.js这个命令
打开浏览器输入这个地址http://localhost:8084/
这样就成功了