Reputation: 3
When I login, I'd like to be able to display the name of the user as a link in my index.jade file, but nothing shows up. I've tried both req.body.username, and req.session, and neither of them have worked. Here's the login controller:
const login = (req, res, next) => {
var username = req.body.username
var password = req.body.password
User.findOne({$or: [{username:username}, {email:username}]})
.then(user => {
if(user) {
bcrypt.compare(password, user.password, function(err, result) {
if(err) {
res.json({
error: err
})
}
if(result) {
//Successful Login
let token = jwt.sign({name: user.name}, 'verySecretValue', {expiresIn: '1h'})
res.redirect('/')
} else {
res.json({
message: 'Password does not match!'
})
}
})
} else {
res.json({
message: 'No user found!'
})
}
})
}
Here's my Routing to the homepage:
var express = require('express');
var router = express.Router();
var mongoose = require('mongoose');
/* GET home page. */
router.get('/', function(req, res, next) {
console.log(req.query)
res.render('index', { title: 'Portfolio', name:req.params.name });
});
module.exports = router;
And a snippet from my index.jade file where I want to insert the data:
extends layout
block content
body
// Topbar Start
.container-fluid
.row.bg-secondary.py-2.px-xl-5
.col-lg-6.d-none.d-lg-block
.d-inline-flex.align-items-center
a.text-dark(href='') **#{req.body.username}**
span.text-muted.px-2 |
a.text-dark(href='') Help
span.text-muted.px-2 |
a.text-dark(href='') Support
Upvotes: 0
Views: 33
Reputation: 16264
First, some comments on your code.
req.params.name
is not in your route for /
. The use of req.params
is for managing a parameterized url, example if you have router.get("/getprofile/:name");
, then a request url of /getprofile/peter
will return "peter" in req.params.name
.
req.body
is present in a Http post request containing the Html control values inside the <form>
in the submitted page. Anyway, you did not pass the req
object to the view page in the render method, so it is not available in index.jade.
Solution:
What you need is to persist the user information across pages. Inside your login code, after the user is securely authenticated, you can use (signed) cookies or session variables to set a user
object to contain your user details:
if(result) {
//Successful Login
let token = jwt.sign({name: user.name}, 'verySecretValue', {expiresIn: '1h'})
res.session.user = { name: user.name, email: "..." };
res.redirect('/')
}
Then you can pass to your view page with something like:
res.render("index", { user: req.session.user });
And in your view page:
a.text-dark(href='') #{user.namme}
Note: you have to first set up express-session
as described in the above link.
Upvotes: 1