[英]node.js - home page doesn't load but other pages do
我正在學習 node.js。 此代碼來自 class。 它有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);
您是否嘗試過在您的情況下使用空字符串“”而不是“/”?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.