'How do I redirect users back to my register <form> with previously filled in information if an error occures when registering?
On my home page I have a button "register" with an onclick event. When clicked a hidden div on that same home page is given "style.display = 'block';" with javascript revealing my registration form. The form takes a username, email, and a password, and when submitted a new user is created and added to my mongoDB database. Then the user gets send to the home page again (same place as they already were, but this makes the div hidden again) Everything works as expected, except for error handling...
Inside my Schema for a new user, I have set it so the username must be unique. This means that when I try to register an account with a username that is already taken, I get an error, meaning the "catch" part of my code is executed. My problem is that I dont know what to type in here to send the user back to the home page with the register form opened and the previously filled in information there along with an error message saying that the username is taken. Is there a way to cancel the form post request and just return back to the previous page? or do I need to structure my code completely differently?
Bonus question: the register button will be available on all my views like on about.html or products.html, how do I redirect the user back to the page he was on when he submitted the form, because now it allways takes you to the index.html
Router:
const router = require("express").Router();
const User = require("../models/User");
const CryptoJS = require("crypto-js");
const jwt = require("jsonwebtoken");
// Register account
router.post("/register", async (req, res) => {
const newUser = new User({
username: req.body.username,
email: req.body.email,
password: CryptoJS.AES.encrypt(req.body.password, process.env.CRYPTO_PASS_SEC).toString()
});
try {
const savedUser = await newUser.save();
res.redirect("../");
} catch (err) {
console.log(err);
console.log("an error occured when registering");
res.redirect(400, "../");
}
});
module.exports = router;
Schema:
const mongoose = require("mongoose");
const UserSchema = new mongoose.Schema({
username: {type: String, required: true, unique: true},
email: {type: String, required: true, unique: true},
password: {type: String, required: true},
isAdmin: {type: Boolean, default: false}
}, {timestamps: true});
module.exports = mongoose.model("User", UserSchema);
html for form:
<div id="dialogRegister" class="dialog"> <!-- Set to display: none; as default -->
<div id="dialogContent">
<div id="btnCloseRegister" class="btnClose">X</div>
<p class="dialogHeader">Create An Account</p>
<form action="/auth/register" method="post">
<div class="formGroup">
<label for="username">Username:</label>
<input type="text" name="username" required>
</div>
<div class="formGroup">
<label for="email">Email:</label>
<input type="email" name="email" required>
</div>
<div class="formGroup">
<label for="password">Password:</label>
<input type="password" name="password" required>
</div>
<div class="btnGroup">
<button type="submit" id="btnRegister" class="btnAuth">Register</button>
<button type="button" id="btnCancelRegister" class="btnCancel">Cancel</button>
</div>
</form>
</div>
</div>
server:
const express = require("express");
const app = express();
const mongoose = require("mongoose");
const dotenv = require("dotenv");
dotenv.config();
const path = require("path");
const methodOverride = require("method-override");
const productsRouter = require("./routes/products");
const authRouter = require("./routes/auth");
mongoose.connect(process.env.MONGO_URL)
.then(() => console.log("Successfully connected to database"))
.catch((err) => console.error(err))
app.set("view engine", "ejs");
app.use('/', express.static(path.join(__dirname, '/public')));
app.use(methodOverride('_method'));
app.use(express.urlencoded({ extended: false }));
app.get("/", (req, res) => {
res.render("home/index");
})
app.use("/products", productsRouter);
app.use("/auth", authRouter);
app.listen(5000);
Javascript:
var btnOpenRegister = document.getElementById("btnOpenRegister");
var btnCloseRegister = document.getElementById("btnCloseRegister");
var btnCancelRegister = document.getElementById("btnCancelRegister");
var btnRegister = document.getElementById("btnRegister");
var dialogRegister = document.getElementById("dialogRegister");
btnOpenRegister.onclick = () => {
dialogRegister.style.display = "block";
}
btnCancelRegister.onclick = () => {
dialogRegister.style.display = "none";
}
btnCloseRegister.onclick = () => {
dialogRegister.style.display = "none";
}
dialogRegister.addEventListener("click", (e) => {
if (e.target === dialogRegister) {
dialogRegister.style.display = "none";
};
});
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
