My code is working but res.redirect()
is not redirecting me to other pages, I am using pug as template engine. this is my first time using pug. (adding this extra text to question because It looks like your post is mostly code; please add some more details.
error is not letting me post lol. )
const express = require("express");
const mongoose = require("mongoose");
const User = require("./model/user");
const bcrypt = require("bcrypt");
const login = require("./routes/login");
const register = require("./routes/register");
const dashboard = require("./routes/dashboard");
const home = require("./routes/home");
const crypto = require("crypto");
const dotenv = require("dotenv").config();
// Connecting Database
mongoose
.connect(process.env.DB, {
useNewUrlParser: true,
useUnifiedTopology: true,
})
.then(() => {
console.log("Database Connected!");
});
const app = express();
// Setting view engine to pug
app.set("view engine", "pug");
// parsing json
app.use(express.json());
// Routes
app.use("/login", login);
app.use("/register", register);
app.use("/dashboard", dashboard);
app.use("/", home);
// creating a new user
app.post("/register", async (req, res) => {
const { username, email, password } = req.body;
const hashedPass = await bcrypt.hash(password, 10);
User.create({
username: username,
email: email,
password: hashedPass,
emailToken: crypto.randomBytes(64).toString("hex"),
});
});
// logging in the user
app.post("/login", async (req, res) => {
const { email, password } = req.body;
const findUser = await User.findOne({ email: email });
console.log(findUser);
if (findUser) {
const match = await bcrypt.compare(password, findUser.password);
if (match) {
console.log("User logged in");
// This is not working
res.redirect("/dashboard");
} else {
console.log("Invalid Password !");
}
} else {
console.log("User not registered !");
}
});
app.listen(process.env.PORT, () => {
console.log("Server to chal gya ji...");
});
This is my pug file for login.
doctype html
html
head
body
form(id="form")
h1 Login
label Email
input(id="email" type="text")
br
br
label Password
input(id="password" type="password")
br
br
input(type="submit" id="btn" value="Login")
br
br
a(href="/register") Register
script
include login.js
And this is login.js from where I am sending a post request using fetch.
const form = document.querySelector("#form");
form.addEventListener("submit", registerUser);
async function registerUser(e) {
e.preventDefault();
const email = document.querySelector("#email").value;
const password = document.querySelector("#password").value;
const output = await fetch("/login", {
method: "POST",
headers: {
"content-type": "application/json",
},
body: JSON.stringify({
email,
password,
}),
});
}
POST /login
request viafetch
. You could redirect with a Javascript command if you writeif (output) location.href = "/dashboard";
– Heiko Theißen