Good morning.
I'm making a node.js application that when logging in should save user attributes (database attributes like name, surname, email, id, etc). But when sending display on the screen, it does not report errors but also the user name. I'm using "express-session" and "cookie-parser".
In the search query, found case and compatible user and password:
req.session.usuario = results; //criando sessao do usuario
res.redirect('/'); //redireciona para index agora logado
I made a test to see if results was getting the right data with a console.dir and everything is ok, it retrieves the attributes of the user in a vector in the index of the name in the database and retrieved value name: x, surname: y]
In the app.js application, there is an app.use function to instantiate the session:
app.use(function(req, res, next){
res.locals.session = req.session.usuario; //para exibir o nome do usuario na tela [partials - menu]
console.dir("res.locals.session>>> "+res.locals.session);
console.dir("req.session.usuario>>> "+req.session.usuario);
res.locals.isLogged = req.session.usuario ? true : false; //se usuario logado = true, se nao = false [layout]
next();
});
I used the consoles.dir to try to see how the items inside res.locals.session and req.session.user are, but in both it just returns strong>
My intention is to retrieve the id and username to
1st - Display the user name in the menu:
if isLogged
li
a(id="tamanhoLinkMenu" href="/logout") Ola, #{session.nome} Logout
ps: The isLogged works perfectly because when the user is logged in it appears "Hello, Logout", but note that the user name does not appear
2nd - Retrieve the id to display to the user only the products that belong to him
If anyone knows what I'm doing wrong and can help or give way, thank you.
Big hug.
edited: Friends, I got some solution to my problem.
It turns out that I'm using the MySQL database and was following an example of a system that used MongoDB.
MySQL returns an array with the results, and to create a user session it apparently needs an object to be instantiated.
Retorno MySQL visto no console:
[RowDataPacket {
id: 1,
nome: x,
sobrenome: y
} ]
In order to save the data I need in the session, it is necessary to convert this array [] to an object {}. Unfortunately I could not do it by hand. I tried to use a function, some conversions for JSON, but none was just in object {} with the indexes and values.
I made a small object in my hand and saved only the items I need right away: ps: As the SQL query should return only 1 user, I know the same is the index [0] of the results
UsuarioDados = {
_id: results[0].usuario_id,
nome: results[0].nome,
sobrenome: results[0].sobrenome
}
And saved the session with:
req.session.usuario = UsuarioDados;
Now, the question may change a little: Does anyone know how to convert the Array [RowDataPacket {index: value, index: value}] into an object only {index: value, index: value} in a way that works by removing the RowDataPacket subscription?