运行服务端node index.js后,在浏览器上输入http://localhost:8888/,服务器根据路径判断,返回默认的页面index.html。浏览器得到index.html后,再依次向服务器请求index.html上需加载的css、js、图片等。服务器根据请求的不同后缀,修改对应响应头部,并返回对应文件。若没有该文件,则返回404界面。
Javascript代码:
const http = require("http");
const fs = require("fs");
const url = require("url");
const path = require("path");
http.createServer((req, res) => {
let pathName = url.parse(req.url).pathname; //转换为url对象
//默认加载路径
if(pathName == '/') {
pathName = "/index.html";
}
//获取文件后缀名
let extName = path.extname(pathName);
// console.log("../fore_end" + pathName); //例如../fore_end/css/style.css
fs.readFile("../fore_end" + pathName, (err, data) => {
if(err) { //出错则返回404页面
console.log("404 Not Found!");
fs.readFile("../fore_end/404.html", (errorNotFound, dataNotFound) => {
if(errorNotFound) {
console.log(errorNotFound);
}
else {
res.writeHead(200, {"Content-Type": "text/html;charset=utf-8"});
res.write(dataNotFound); //返回404页面
res.end();
}
})
return;
}
else {
// 获取对应后缀的文件类型
let ext = getExt(extName);
// 设置请求头
res.writeHead(200, {"Content-Type": ext + "; charset=utf-8"});
res.write(data); //返回请求文件
res.end();
}
})
}).listen(8888);
// 获取后缀名
getExt = (extName) => {
switch(extName) {
case '.html': return 'text/html';
case '.css': return 'text/css';
case '.js': return 'text/js';
default: return 'text/html';
}
}
要注意,上面返回文件的路径是相对于服务端的index.js文件。
要获取更多的文件类型,可通过读取文件判断。ext.json文件获取
getExt = (extName) => {
let data = fs.readFileSync("./ext.json");
let ext = JSON.parse(data.toString()); //转换为js对象
return ext[extName];
}
对于浏览器请求的 favicon.icon文件,可在html头部添加下面部分。浏览器会向服务器请求favicon.icon
<link rel="shortcut icon" href="img/favicon.icon" />
参考链接:
https://github.com/LiangJunrong/document-library/blob/master/other-library/Node/Node-base.md#chapter-three-ten
https://blog.csdn.net/guzhao593/article/details/93972193(网站 favicon.icon图标的设置)