admin管理员组

文章数量:1399887

I'm currently trying to make a login and signup form using EJS, Express, Node, etc. However Whenever I submit data from a form, all data is being returned as "Invalid" I've checked my user Model and Routes for typos and can't seem to find anything.

Here is my app.js

const express = require('express');
const mongoose = require('mongoose');
const cookieParser = require('cookie-parser');
const bodyParser = require('body-parser')
const loginRoutes = require('./routes/loginRoutes');
const signupRoutes = require('./routes/signupRoutes');
const logoutRoutes = require('./routes/logoutRoutes');
const app = express();
const path = require('path');


class Server {
    constructor() {
        this.app = express();
        this.port = process.env.PORT || 3000;
        this.app.use(express.json()); // Use Middleware to parse JSON Bodies
        this.path = path;

        this.setRendering();
        this.configRoutes();
        this.connectDB();
        this.serverSetup();
    }

    setRendering() {
        app.use(bodyParser.urlencoded({ extended: true }));
        app.set('views', path.join(__dirname, './frontend/views'))
        app.set('view engine', 'ejs');
        app.use(express.static(path.join(__dirname, './frontend/static')));
        app.use(express.json())

    }

    configRoutes() {
        app.get('/', (req, res) => {
            res.render('./index')
        });

        app.use('/auth', loginRoutes, signupRoutes, logoutRoutes)
        app.get('*', (req, res) => {
            res.send('Page Not Found, check your spelling or routes');
        })
    }

    connectDB() {
        const URL = 'mongodb://localhost:27017/collection';
        typeof(URL);
        require('dotenv').config();
        mongoose.connect(URL, {
            useNewUrlParser: true,
            useUnifiedTopology: true,
        })
        .then(() => {
            console.log(`Connected to MongoDB at the following URL: ${URL}`)
        })
        .catch((err) => {
            console.error('Error conencting to MongoDB:', err);
        });

        mongoose.connection.on('error', (err) => {
            console.error('MongoDB Connection Error:', err);
        });
        mongoose.connection.once('open', () => {
            console.log('Connection established');
        });
        mongoose.connection.on('disconnected', () => {
            console.log('Sucessfully Disconnected from MongoDB');
        });

        // Handling Connection Closure
        process.on('SIGINT', () => {
            mongoose.connection.close(() => {
                console.log('Mongoose Connection automatically Disconnected due to process termination.');
                process.exit(0);
            });
        });
    }

    serverSetup() {
        app.listen(this.port, () => {
            console.log(`server running at http://localhost:${this.port}/`)
        })
    }

}

new Server();

My signup.ejs

<!DOCTYPE html>
<html>
    <head>
        <title>ROLSA | Signup</title>
        <link rel="stylesheet" href="/css/signup.css">
    </head>
    <body>
        <div class="container">
            <div class="greeting-card">
                <h1 class="welcome">Welcome to<br>ROLSA Technologies</h1>
                <br>
                <h2 class="page-descriptor">SIGNING UP</h2>
                <a href="/signup">Alreadyhave an account? Click me</a>
            </div>
            <div class="form">
                <form action="/auth/signup" method="POST">
                    <label for="firstName">First Name</label>
                    <input type="text" id="firstName" name="firstName" required placeholder="John">
                    <label for="lastName">Last Name</label>
                    <input type="text" id="lastName" name="lastName" required placeholder="Doe">

                    <label for="address">Address</label>
                    <input type="text" id="address" name="address" required placeholder="123 Example Street">

                    <label for="email">Email</label>
                    <input type="email" id="email" name="email" required placeholder="email">
                    <% if (emailError) { %>
                        <p class="error-message"><%= emailError %></p>
                        <% } %>
                    <% if (passError) { %>
                        <p class="error-message"><%= passError %></p>
                        <% } %>
                    <label for="password">Password</label>
                    <input type="password" id="password" name="password" required>
                    <button type="submit" value="signup">Sign Up</button>
                </form>
            </div>
        </div>
    </body>
</html>

my signup route and controller

const express = require('express');
const router = express.Router();
const bcrypt = require('bcrypt');
const User = require('../backend/database/models/user')

router.get('/signup', (req, res) => {
    res.render('./signup', { title: 'Signup', emailError: null, passError: null});

});

router.post('/signup', async (req, res) => {
    const { email, password, firstName, lastName, address } = req.body;
    console.log(typeof(password));
    console.log(typeof(email));
    try {
        const existingUser = await User.findOne({ email });
        if (existingUser) {
            return res.render('./signup', {
                emailError: 'Email already Exists',
                title: 'Sign Up',
                passError: null
            })
        }
        /* console.log(password);
        console.log(typeof(password)); */
        if(password.length < 8) {
            return res.render('./signup', {
                title: 'Sign Up',
                passError: 'Password must be at least 8 characters long',
                emailError: null
            })
        }
        const salt = await bcrypt.genSalt(10);
        const hashedPassword = await bcrypt.hash(password, salt)
        const newUser = new User({ email, password: hashedPassword, firstName, lastName, address });
        await newUser.save();
        res.redirect('/login')
    } catch (err) {
        console.log(err);
        res.redirect('/auth/signup');

    }
});

module.exports = router;

I've tried adding debugging statements to see where the issue is occurring, but the values are "undefined" throughout. I've tried other forum posts and have had no success.

本文标签: