I am trying to use Express router in order to have my app.js file be less packed with code but I am having issues getting it to route to the correct place.
The page that it should be routed to is localhost:5000/users/login but it is instead routing localhost:5000/login.
I was referencing the Vidjot project from Brad Traversy's Udemy course and trying to set it up the same way but it does not seem to work even though the code is the same.
Below is the code for the app.js file and my users.js file which I am trying to route from.
// 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;
The expected result is that it should route to localhost:5000/users/login and localhost:5000/users/register instead of localhost:5000/users and localhost:5000/register. There are no error messages which are appearing.