首页 > 解决方案 > The main index page loads on localhost:3000, but localhost:3000/index and localhost:3000/login return "Cannot GET /index" and "Cannot GET /login"

问题描述

My directory looks like this:


The issue is that while localhost:3000 is loading the correct index page, localhost:3000/index is not, instead showing "cannot GET /index" and the same issue is happening with localhost:3000/login


I am pretty new so I'm following a tutorial for handlebars/express, the code below is almost exactly how it was written in the tutorial. The only thing I can think of is potentially an update to handlebars broke something here? Thanks for any answers guys

const express = require('express');
const session = require('express-session');
const hbs = require('express-handlebars');
const mongoose = require('mongoose');
const passport = require('passport');
const localStrategy = require('passport-local').Strategy;
const bcrypt = require('bcrypt');
const app = express();

mongoose.connect('theurlformymongodb', {
    useNewUrlParser: true,
    useUnifiedTopology: true
});

const UserSchema = new mongoose.Schema({
    username: {
        type: String,
        required: true
    },
    password: {
        type: String,
        required: true
    }
});

const User = mongoose.model('User', UserSchema);

// 

app.engine('hbs', hbs({ extname: '.hbs'}));
app.set('view engine', 'hbs');
app.use(express.static(__dirname + '/public'));
app.use(session({
    secret: "placeholdersecretkey",
    resave: false,
    saveUninitialized: true
}));

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

// passport stuff

app.use(passport.initialize());
app.use(passport.session());

passport.serializeUser(function (user, done) {
    done(null, user.id)
});

// idk 
passport.deserializeUser(function (id, done) {
    User.findById(id, function (err, user) {
        done(err, user)
    });
});

passport.use(new localStrategy(function (username, password, done) {
    User.findOne({ username: username }, function (err, user) {
        if (err) return done(err); 
        if (!user) return done(null, false, { message: 'Incorrect username.' }); 

           bcrypt.compare(password, user.password, function (err, res) {
                if (err) return done(err);
                if (res === false)  return done(null, false, {message: 'Incorrect password.'});

                return done(null, user); 
           }); 
    });
}));

// ROUTES
app.get('/', (req, res) => {
    res.render("index", { title: "Home" });
});

app.get('/', (req, res) => {
    res.render('login', { title: "Login" });
});

app.listen(3000, () => {
    console.log('Listening on port 3000');
});

标签: htmlnode.jsexpresshandlebars.js

解决方案


推荐阅读