I've multiple newbie questions regarding Nodejs.
I've build api for the auth/login and i'm questionning about the connection frontend and backend. so first, I would like to know in my form the action, should I put the url of my api? or another route?
<div class="container">
<div class="boxlogin">
<img id="img-logo" src="img/logo.png" alt="Logo">
<h1>Sign in</h1>
<div class="alert alert-warning alert-dismissible fade show" role="alert">
<button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
</div>
<form action="????" method="POST">
<input type="email" name="email" id="email" placeholder="Email" class="input-box" required>
<input type="password" name="password" id="password" placeholder="Password" class="input-box" required>
<button type="submit" class="btn-signup">Log in</button>
<p class="compte-deja-cree">Don't have an Account yet ? <a href="/signup-user.ejs">Sign In</a></p>
</form>
</div>
<div class="imglogin"><img id="img-login" src="img/undraw_Active_support_re_b7sj.svg" alt="Logologin"></div>
</div>
also in my controller there is a try catch, I would like to display the errors (err of password, or err of email) and I don't know at all how I have to do it.
For information i'm using nodejs/mongodb/express/ejs.
here some pieces of my code for understanding.
server.js
app.use("/css", express.static(__dirname "public/css"));
app.use("/img", express.static(__dirname "public/img"));
app.set("view-engine", "ejs");
app.get("*", checkUser);
app.get("/jwtid", requireAuth, (req, res) => {
res.status(200).send(res.locals.user._id);
});
const userRoutes = require("./routes/user.routes");
const mainRoutes = require("./routes/main.routes");
app.use("/api/user", userRoutes);
app.use('/', mainRoutes);
authController :
const SellerModel = require("../models/sellerModel");
const SuperUserModel = require("../models/superUserModel");
const UserModel = require("../models/userModel");
const LoginModel = require("../models/loginModel");
const jwt = require("jsonwebtoken");
const { signUpErrors, signInErrors } = require("../utils/errorsUtils");
const maxAge = 3 * 24 * 60 * 60 * 1000;
const createToken = (id) => {
return jwt.sign({ id }, process.env.TOKEN_SECRET, {
expiresIn: maxAge,
});
};
module.exports.sellerSignUp = async (req, res) => {
const {company,email,password,telephone,address,zipcode,city} = req.body;
try {
const user = await SellerModel.create({company,email,password,telephone,address,zipcode,city});
res.redirect("/");
} catch (err) {
const errors = signUpErrors(err);
res.status(200).send({ errors });
}
};
module.exports.userSignUp = async (req, res) => {
const {email,password,telephone,address,zipcode,city} = req.body;
try {
const user = await UserModel.create({email,password,telephone,address,zipcode,city});
res.redirect("/");
} catch (err) {
const errors = signUpErrors(err);
res.status(200).send({ errors });
}
};
module.exports.superUserSignUp = async (req, res) => {
const { email, password } = req.body;
try {
const user = await SuperUserModel.create({ email, password });
res.redirect("/");
} catch (err) {
const errors = signUpErrors(err);
res.status(200).send({ errors });
}
};
module.exports.signIn = async (req, res) => {
const { email, password } = req.body;
try {
const user = await LoginModel.login(email, password);
const token = createToken(user._id);
res.cookie("jwt", token, { httpOnly: true, maxAge });
if (user.role == "seller") {
res.redirect("/success");
} else if (user.role == "user") {
res.redirect("/success-user");
} else if (user.role == "superuser") {
res.redirect("/success-admin");
};
} catch (err) {
const errors = signInErrors(err);
res.status(200).json({ errors });
}
};
module.exports.logout = (req, res) => {
res.cookie("jwt", "", { maxAge: 1 });
res.redirect("/");
};
user.routes:
const router = require("express").Router();
const authController = require("../controllers/authController");
router.post("/register/seller", authController.sellerSignUp);
router.post("/register/user", authController.userSignUp);
router.post("/register/admin", authController.superUserSignUp);
router.post("/login", authController.signIn);
router.get("/logout", authController.logout);
module.exports = router;
main.routes:
const router = require("express").Router();
router.get("/", (req, res) => {
res.render("login.ejs");
});
router.get("/signup-user", (req, res) => {
res.render("signup-user.ejs");
});
router.get("/signup-seller", (req, res) => {
res.render("signup-seller.ejs");
});
router.get("/success", (req, res) => {
res.render("sucessful.ejs");
});
router.get("/success-user", (req, res) => {
res.render("sucessful-user.ejs");
});
router.get("/success-admin", (req, res) => {
res.render("sucessful-admin.ejs");
});
module.exports = router;
Wish you a awesome Sunday !
CodePudding user response:
To resolve this, I add some dependencies : connect-flash express-session express-messages
in my Server.js
app.use(session({
secret:"Secret",
cookie:{ maxAge : 60000},
resave: false,
saveUninitialized: true,
}))
app.use(flash());
app.use(require('connect-flash')());
app.use(function (req,res,next){
res.locals.messages = require('express-messages')(req,res);
next();
})
app.use(express.static("public"));
in authController
module.exports.sellerSignUp = async (req, res) => {
const {company,email,password,telephone,address,zipcode,city} = req.body;
try {
const user = await SellerModel.create({company,email,password,telephone,address,zipcode,city});
req.flash('info', `Successful Register`)
res.redirect("/");
} catch (err) {
const errors = signUpErrors(err);
console.log(errors);
req.flash('message', errors.email || errors.password );
res.redirect('/register-seller');
}
};
in my main route :
const router = require("express").Router();
const services = require('../service/render');
router.get("/", services.login);
router.get("/register-user",services.registerUser);
router.get("/register-seller",services.registerSeller);
router.get("/success",services.sucessful);
router.get("/success-user",services.sucessfull_t);
router.get("/success-admin",services.sucessful_a);
module.exports = router;
render.js:
exports.login = (req, res) => {res.render("login.ejs",{ errorMessage: req.flash('message'), successMsg: req.flash('info') })};
exports.registerUser = (req, res) => {res.render("register-user.ejs",{ message: req.flash('message')})};
exports.registerSeller = (req, res) => {res.render("register-seller.ejs",{ message: req.flash('message')})};
exports.sucessful = (req, res) => {
res.render("sucessful.ejs");
};
exports.sucessfull_t = (req, res) => {
res.render("sucessful-t.ejs");
};
exports.sucessful_a = (req, res) => {
res.render("sucessful-a.ejs");
};