I’m making an application with Node.JS and while I was trying to redirect a user from the login page to another page, nothing was happening.
I used this login function where I use res.redirect(307, "/home/userPAGE")
to redirect the user:
const login = asyncHandler (async (req, res) => {
const {email, password} = req.body;
if (!email || !password){
res.status(400);
throw new Error("Email or password not provided");
}
const user = await User.findOne({email});
if (user && (await bcrypt.compare(password, user.password))) {
const accessToken = jwt.sign({
user: {
username: user.id,
email: user.email,
id: user.id
},
}, process.env.ACCESS_TOKEN_SECRET,
{expiresIn: "30m"});
console.log("Logged in!");
res.redirect(307, "/home/userPAGE");
}
else {
res.status(400);
throw new Error("Email or Password is not valid");
}
});
Then, this path should loat my userpage.html file:
app.use("/home/userPAGE", (req, res) => {
console.log("HERE")
res.sendFile(path.join(__dirname, "./public/userpage.html"));
});
but it doesn’t. If I look at the logs I see HERE
, but nothing happens after.
I’ve looked through other’s posts, but it looks like I have similar code to people in the solutions, so I’m confused to what the problem is.
This was one of the answers:
var express = require("express");
var bodyParser = require("body-parser");
var app = express();
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use(express.static(__dirname + "/public/arena.html"));
app.get('/', function(req, res) {
res.sendFile(__dirname + "/public/index.html");
});
app.get('/arena', function(req, res) {
res.sendFile(__dirname + "/public/arena.html");
});
app.post('/login', function(req, res) {
var username = req.body.username;
console.log("User name = " + username);
// Note how I'm redirecting the user to the /arena URL.
// When you issue a redirect, you MUST redirect the user
// to a webpage on your site. You can't redirect them to
// a file you have on your disk.
res.redirect("/arena");
});
app.listen(3000);