实现 多个同学的作业部署 访问 /A 返回A的网页 访问 /B 返回B的网页
思路 根据 发送请求的路径 判断应该读区哪个文件夹中的哪个文件
例如 hongbin.xyz:3002/abc 应当返回 /zbc/index.html 文件
html文件 引入的index.css 请求的路径是hongbin.xyz:3000/index.css 没办法确定css文件所属目录 应当返回 /zbc/index.css 问题: req.url 是index.css 怎么确定是/abc 目录下的index.css 文件 解决: req.headers.referer 是发起请求的地址 为hongbin.xyz:3002/abc 通过referer 判断是哪个文件目录下的文件
css中的 background:url(./images/1.png) 应当返回 /zbc/images/1.png 但是发起请求的是index.css 文件 referer 为hongbin.xyz:3002/index.css 解决部署前换成 绝对地址 background:url(abc/images/1.png) 直接返回 abc/images/1.png
代码:
const express = require("express");
const fs = require("fs");
const http = require("http");
const app = express();
const path = require('path');
const port = process.env.PORT || 3000;
app.all("*", function (req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "content-type,Authorization");
res.header("Access-Control-Allow-Methods", "DELETE,PUT,POST,GET,OPTIONS");
if (req.method.toLowerCase() == "options") res.status(200).send();
else next();
});
const httpServer = http.createServer(app);
httpServer.listen(port, () => { console.log("> dev mode on http " + port) });
let fileNames = fs.readdirSync('../source');
app.get('/updateFileDir', (req, res) => {
fileNames = fs.readdirSync('../source');
return res.json({ message: '更新成功', fileNames });
})
app.get("/*", (req, res, next) => {
let pathName = req.url;
pathName = pathName.substring(0, pathName.indexOf('?') === -1 ? pathName.length : pathName.indexOf('?'));
const dirName = pathName.substring(1);
console.log(pathName);
let referer = req.headers?.referer ?? "";
referer = referer.substring(0, referer.indexOf('?') === -1 ? referer.length : referer.indexOf('?'));
const reqSource = referer.replace('http://' + req.headers.host, '');
if (fileNames.includes(dirName)) {
req.fileName = dirName;
pathName += "/index.html";
} else if (fileNames.includes(reqSource?.substring(1))) {
pathName = `${reqSource}${pathName}`;
} else {
if (pathName.split('/')[1] && fileNames.includes(pathName.split('/')[1])) {
console.log("绝对路径:", pathName);
} else return res.status(404).json("未找到资源");
}
console.log(pathName);
const extName = path.extname(pathName);
fs.readFile(`../source${pathName}`, function (err, data) {
if (err) {
console.error(err);
res.status(400).json(err);
} else {
const ext = getExt(extName);
res.writeHead(200, { "Content-Type": ext + "; charset=utf-8" });
res.write(data);
}
res.end();
});
});
const EXT = {
".html": "text/html",
".css": "text/css",
".js": "text/js",
".ico": "image/x-icon",
".png": "image/png",
".svg": "image/svg",
};
getExt = extName => {
return EXT[extName];
};
|