Здравствуйте. Пишу HTTP-сервер и веб-интерфейс к нему. Вот код:
./web_ui/index.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>index</title>
<link rel="stylesheet" href="styles/main.css">
</head>
<body>
index
</body>
</html>
./main.js:
const net = require("node:net");
const fs = require('node:fs');
const fsPromises = require("node:fs/promises");
const path = require("node:path");
function generateServerAnswer(httpStatus, body, headers) {
let t = `HTTP/1.1 ${httpStatus[0]} ${httpStatus[1]}\r\n`;
if (headers) {
for (let key in headers) {
t += `${key}: ${headers[key]}\r\n`;
}
}
t += "\r\n";
return typeof(body) === 'string' && body.length > 0 ? `${t}${body}` : t;
}
async function sendFile(client, filePath) {
console.log(filePath);
if (fs.existsSync(filePath)) {
const fileStats = fs.statSync(filePath);
if (fileStats) {
const headers = { "Content-Length": fileStats.size.toString() };
const ext = path.extname(filePath).toLowerCase();
switch (ext) {
case ".html":
headers["Content-Type"] = "text/html";
break;
}
client.write(generateServerAnswer([200, "OK"], null, headers));
const buffer = await fsPromises.readFile(filePath);
if (buffer) { client.write(buffer); }
}
} else {
client.write(generateServerAnswer([404, "Not Found"], "File is not found"));
}
}
function getSocketAddress(socket) {
return `${socket.remoteAddress}:${socket.remotePort}`;
}
async function processClient(client, requestedPath) {
await sendFile(client, requestedPath);
}
const server = net.createServer(client => {
console.log(`Client ${getSocketAddress(client)} is connected`);
client.on("end", () => console.log(`Client ${getSocketAddress(client)} is disconnected`));
client.on("data", async data => {
const splitted = data.toString().split("\r\n");
const requestedPath = splitted[0].split(" ")[1];
await processClient(client, requestedPath.substring(1));
client.end();
});
});
server.listen(5556, () => console.log("server is started"));
Если заходить по адресу http://127.0.0.1:5556/web_ui/index.html
- всё работает.
Но я хочу сделать перенаправление. Чтобы, например, можно было ввести просто http://127.0.0.1:5556
и тебя перекинуло на index.html
. Для этого модифицирую функцию:
async function processClient(client, requestedPath) {
const filePath = requestedPath ? requestedPath : "web_ui/index.html";
await sendFile(client, filePath);
}
Теперь если зайти по адресу http://127.0.0.1:5556
- грузится index.html
. Но не грузится css
ка. Серверу приходит запрос GET /styles/main.css
вместо GET /web_ui/styles/main.css
. И, соответственно, file not found
Если прописать полный путь <link rel="stylesheet" href="/web_ui/styles/main.css">
- тогда работает. Но не менять же пути во всех страницах, если я захочу переименовать папку с веб-интерфейсом?