我正在尝试使用Express路由器,以使我的app.js文件减少代码包装,但是在将其路由到正确的位置时遇到问题。
应该路由到的页面是localhost:5000 / users / login,但是却路由localhost:5000 / login。
我从Brad Traversy的Udemy课程中引用了Vidjot项目,并试图以相同的方式进行设置,但是即使代码相同,它似乎也不起作用。
下面是我试图从中路由的app.js文件和我的users.js文件的代码。
// Import and initialize express.
const express = require("express");
const app = express();
// Import necessary modules.
const mongoose = require("mongoose");
const path = require("path");
const exphbs = require("express-handlebars");
// Load routes.
// const gifs = require('./routes/gifs');
const users = require("./routes/users");
// Connect to mongoose.
mongoose
.connect("mongodb://localhost/giphy-saver", {
useMongoClient: true
})
.then(() => {
console.log("MongoDB Connected...");
})
.catch(err => {
console.log(err);
});
// Static folder.
app.use(express.static(path.join(__dirname, "public")));
// Handlebars middleware.
app.engine(
"handlebars",
exphbs({
defaultLayout: "main"
})
);
app.set("view engine", "handlebars");
// Routes.
app.get("/", (req, res) => {
res.render("index", { title: "Giphy Saver" });
});
app.get("/about", (req, res) => {
res.render("about", { title: "About" });
});
// Use routes.
app.use("/users", users);
const PORT = process.env.PORT || 5000;
app.listen(PORT);
const express = require("express");
const mongoose = require("mongoose");
// Used for password encryption.
const bcrypt = require("bcryptjs");
// Used for authentication.
const passport = require("passport");
const router = express.Router();
// Load the User model.
require("../models/User");
const User = mongoose.model("users");
// User login route.
router.get("/login", (req, res) => {
res.render("users/login", { title: "Login" });
});
// User registration route.
router.get("/register", (req, res) => {
res.render("users/register", { title: "Register" });
});
module.exports = router;
预期结果是它应该路由到localhost:5000 / users / login和localhost:5000 / users / register,而不是localhost:5000 / users和localhost:5000 / register。没有出现错误消息。
答案 0 :(得分:0)
您在HTML文件中使用href="/users/login"
和href="/users/register"
吗?
还是您在导航栏中使用了href="/login"
?