主页无法加载,但其他页面加载

  • 本文关键字:加载 其他 主页 node.js
  • 更新时间 :
  • 英文 :


我正在学习node.js。这段代码来自一个类。它有if else语句。重点是简化它,我正在做的一种方法是使用switch case。我不确定为什么主页没有加载;其他页面";以及其他页面";做

作为次要问题,figlet在windows上工作吗?我在node_modules文件夹中使用npm install figlet。不确定我是否可以在一个线程中发布多个问题。如果没有,我想先解决我的主页。

const http = require("http");
const fs = require("fs");
const url = require("url");
const querystring = require("querystring");
// const figlet = require("figlet");
const server = http.createServer((req, res) => {
const page = url.parse(req.url).pathname;
const params = querystring.parse(url.parse(req.url).query);
console.log(page);
switch (page) {
case "/":
fs.readFile("index.html", function (err, data) {
res.writeHead(200, { "Content-Type": "text/html" });
res.write(data);
res.end();
});
break;
case "/otherpage":
fs.readFile("otherpage.html", function (err, data) {
res.writeHead(200, { "Content-Type": "text/html" });
res.write(data);
res.end();
});
break;
case "/otherotherpage":
fs.readFile("otherotherpage.html", function (err, data) {
res.writeHead(200, { "Content-Type": "text/html" });
res.write(data);
res.end();
});
break;
case "/api":
if ("student" in params) {
if (params["student"] == "leon") {
res.writeHead(200, { "Content-Type": "application/json" });
const objToJson = {
name: "leon",
status: "Boss Man",
currentOccupation: "Baller",
};
res.end(JSON.stringify(objToJson));
} else if (params["student"] != "leon") {
res.writeHead(200, { "Content-Type": "application/json" });
const objToJson = {
name: "unknown",
status: "unknown",
currentOccupation: "unknown",
};
res.end(JSON.stringify(objToJson));
}
}
break;
case "/ccs/style.css":
fs.readFile("css/style.css", function (err, data) {
res.write(data);
res.end();
});
break;
case "/js/main.js":
fs.readFile("js/main.js", function (err, data) {
res.writeHead(200, { "Content-Type": "text/javascript" });
res.write(data);
res.end();
});
break;
default:
figlet("404!!", function (err, data) {
if (err) {
console.log("Something went wrong...");
console.dir(err);
return;
}
res.write(data);
res.end();
});
}
});
server.listen(8000);

您是否尝试过使用空字符串"quot;而不是"/"在你的情况下?

最新更新