使用node.js登录之后获取到session中的id,并根据id查询mysql数据库,获取到登录用户名,并使用art-template模板引擎传递给客户端的前后端代码
时间: 2023-06-27 08:04:26 浏览: 49
以下是一个简单的示例代码,实现了使用Node.js登录,获取Session中的ID,查询MySQL数据库获取用户名,并使用art-template模板引擎渲染页面并传递给客户端。
```
const express = require('express');
const session = require('express-session');
const mysql = require('mysql');
const template = require('art-template');
const app = express();
// 设置Session
app.use(session({
secret: 'my secret key',
resave: false,
saveUninitialized: true,
cookie: { secure: false }
}));
// 连接MySQL数据库
const connection = mysql.createConnection({
host: 'localhost',
user: 'root',
password: 'password',
database: 'mydatabase'
});
connection.connect();
// 处理登录请求
app.post('/login', (req, res) => {
const { username, password } = req.body;
// 验证用户名和密码
if (username === 'admin' && password === '123456') {
// 登录成功,将用户ID存入Session
req.session.userId = 1;
res.redirect('/dashboard');
} else {
res.send('Invalid username or password');
}
});
// 处理仪表盘页面请求
app.get('/dashboard', (req, res) => {
const userId = req.session.userId;
// 如果用户未登录,重定向到登录页面
if (!userId) {
res.redirect('/login');
return;
}
// 查询MySQL数据库获取用户名
connection.query(`SELECT username FROM users WHERE id=${userId}`, (err, result) => {
if (err) throw err;
const username = result[0].username;
// 使用art-template模板引擎渲染页面并传递用户名
const html = template.render(`
<html>
<head>
<title>Dashboard</title>
</head>
<body>
<h1>Welcome, {{username}}!</h1>
</body>
</html>
`, { username });
res.send(html);
});
});
// 启动服务器
app.listen(3000, () => {
console.log('Server started on port 3000');
});
```
上述代码中,使用了`express-session`模块来管理Session,使用`mysql`模块连接MySQL数据库,使用`art-template`模板引擎渲染页面。
在处理登录请求时,如果用户名和密码验证通过,将用户ID存入Session中。在处理仪表盘页面请求时,首先检查用户是否已登录,然后根据Session中的用户ID查询MySQL数据库获取用户名。最后使用`art-template`模板引擎渲染页面并传递用户名。