繁体   English   中英

node.js - 主页不加载,但其他页面加载

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM