执行 get 请求时 Express 服务器没有挂起

问题描述 投票:0回答:1

大家好,我希望你们做得很好,请有人帮助我解决这个问题,我不知道问题是什么,我是 Express 的新手,节点试图创建一本学习日记,我创建了正常的页面,一旦开始,每个人都开始正常创建管理页面时,当我执行任何请求时,一切都不再起作用 localhost/PORT 不起作用 localhost/PORT/admin 似乎不起作用,这里是我的 app.js ( main ) 代码和我的路由处理程序我将一个名为“routes”的文件夹保存在同一目录中,请帮助我,我真的需要它

图片中附有工作树

控制台中没有错误,所以我希望一切正常,页面正常渲染,但什么也没有发生,没有页面渲染,并且获取请求的回调函数没有执行,我用一个简单的控制台日志检查了这一点

const express = require("express");
const mongoose = require("mongoose");
const expressLayout = require("express-ejs-layouts");
const bodyParser = require("body-parser");
//help us to store our login cession so we don't have to log in everytimeconst
cookieParser = require("cookie-parser");
const session = require("express-session");
const MongoStore = require("connect-mongo");
const Blog = require("./models/blog");
const User = require("./models/user");

mongoose.set("strictQuery", false);
/*when you perform queries using Mongoose,you can specify fields that are not defined in the schema,and Mongoose will not throw an error if these fields are presentin the documents being queried. */

const app = express();

app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use(cookieParser);

if (process.env.NODE_ENV !== "production") {
  require("dotenv").config();
}

const PORT = process.env.PORT || 3000;

const CONNECTION = process.env.CONNECTION;

app.use(
  session({
    secret: "keyboard cat",
    resave: false,
    saveUninitialized: true,
    store: MongoStore.create({ mongoUrl: CONNECTION }),
  })
);

app.use(express.static("../public"));

//set a public folder

app.use(expressLayout);
app.set("layout", "./layouts/main");
app.set("view engine", "ejs");

//link to the routes files

app.use("/", require("./routes/main"));
app.use("/", require("./routes/admin"));

app.use((req, res) => {
  res.type("text/plain");
  res.status(404);
  res.send("404 - Not Found");
});
app.use((err, req, res, next) => {
  console.error(err.stack);
  res.status(500).send("Something broke!");
});

const start = async () => {
  try {
    await mongoose.connect(CONNECTION);
    app.listen(PORT, () => {
      console.log("server is running on port" + PORT);
    });
  } catch (e) {
    console.log(e.message);
  }
};

start();

// main.js (routes for all users ) 

const express = require("express");
const router = express.Router();
const mongoose = require("mongoose");
const Blog = mongoose.model("Blog"); // Assuming you've defined your Blog model
// blogs data
//routes
/* GET HOME  */
router.get("", async (req, res) => {
  const locals = {
    title: "Home Page",
  };
  try {
    console.log("am here");
    let perPage = 8;
    let page = req.query.page || 1;
    //const data = await Blog.find()
    const data = await Blog.aggregate([{ $sort: { createdAt: -1 } }])
      .skip(perPage * page - perPage)
      .limit(perPage)
      .exec();

    const count = await Blog.count();
    const nextPage = parseInt(page) + 1;
    const hasNextPage = nextPage <= Math.ceil(count / perPage);

    res.render("index", {
      data,
      locals,
      current: page,
      nextPage: hasNextPage ? nextPage : null,
    });
    // Fetch all blogs from the database
  } catch (error) {
    console.error(error);
    res.status(500).send("Internal Server Error");
  }
});
/* GET ABOUT */
router.get("/about", async (req, res) => {
  const locals = {
    title: "About Page",
  };
  const data = await Blog.aggregate([{ $sort: { createdAt: -1 } }]);
  res.render("about", { data, locals });
});

/* GET Blog:id */
router.get("/blog/:id", async (req, res) => {
  try {
    let slug = req.params.id;
    const data = await Blog.findById({ _id: slug });
    const locals = {
      title: data.title,
    };
    res.render("blog", { data, locals });
  } catch (error) {
    console.error(error);
    res.status(500).send("Internal Server Error");
  }
});

//export the router
module.exports = router;
// Admin.js

const express = require("express");
const router = express.Router();
const mongoose = require("mongoose");
const Blog = mongoose.model("Blog"); // Assuming you've defined your Blog model
const User = mongoose.model("User");
const adminLayout = "../views/layouts/admin";
//this is will help us decript the password so we can store it in the db
const bcrypt = require("bcrypt");
//you should store plain text passwords in ur db
const jwt = require("jsonwebtoken");
/*
 * GET /
 * Admin-Login Page
 */

router.get("/admin", async (req, res) => {
  try {
    const locals = {
      title: "Admin Page",
    };

    res.render("admin/login", { locals, layout: adminLayout });
  } catch (error) {
    console.error(error);
  }
});
router.post("/admin", async (req, res) => {
  const { username, password } = req.body;
  console.log(username);
  console.log(password);
  const hashedPassword = await bcrypt.hash(password);
  try {
    const user = await User.create({ username, hashedPassword });
    res.status(201).json({ message: "User Created", user });
  } catch (error) {
    if (error.code === 11000) {
      res.status(409).json({ message: "User already in use" });
    }
    res.status(500).json({ message: "Internal server error" });
  }
  res.redirect("/admin");
});

module.exports = router;
javascript node.js express view server
1个回答
0
投票

你在这里有依赖性问题:

if (process.env.NODE_ENV !== "production") {
  require("dotenv").config();
}

您的

if()
语句依赖于可用于与字符串
process.env.NODE_ENV
进行比较的
production
变量。但是,为了访问
NODE_ENV
值,您首先需要导入
dotenv
模块。好吧,在您的情况下,除非
NODE_ENV
等于
production
,否则您不会导入它。你看到问题了吗?

连锁效应是你的监听器永远不会执行,因为这里:

const CONNECTION = process.env.CONNECTION;

CONNECTION
将是
undefined
,因为您之前无法导入
dotenv
。所以当你尝试在这里使用
CONNECTION
时:

await mongoose.connect(CONNECTION);
app.listen(PORT, () => {
   console.log("server is running on port" + PORT);
});

它应该抛出一个错误。

只需将

require("dotenv").config();
语句移出
if()
语句即可。

© www.soinside.com 2019 - 2024. All rights reserved.