MySQL与Node.js:全栈开发实践
warning:
这篇文章距离上次修改已过203天,其中的内容可能已经有所变动。
// 使用Node.js和MySQL创建一个简单的用户注册系统
// 引入所需模块
const crypto = require('crypto');
const mysql = require('mysql');
// 配置MySQL连接
const connection = mysql.createConnection({
host: 'localhost',
user: 'your_username',
password: 'your_password',
database: 'your_database'
});
// 连接到MySQL
connection.connect();
// 创建注册新用户的函数
function createNewUser(email, password) {
// 生成随机的salt和hash
const salt = crypto.randomBytes(16).toString('hex');
const hash = crypto.pbkdf2Sync(password, salt, 100000, 64, 'sha512').toString('hex');
// 插入新用户到数据库
connection.query('INSERT INTO users (email, password_hash, password_salt) VALUES (?, ?, ?)', [email, hash, salt], (error, results, fields) => {
if (error) throw error;
console.log('User created with ID:', results.insertId);
});
}
// 假设有POST请求提交了用户注册信息
const userEmail = 'user@example.com'; // 用户提交的邮箱
const userPassword = 'userPassword'; // 用户提交的密码
// 创建新用户
createNewUser(userEmail, userPassword);
// 关闭MySQL连接
connection.end();
这段代码展示了如何在Node.js环境中使用MySQL模块来连接MySQL数据库,并创建一个新用户注册系统。它使用了crypto模块来生成密码哈希,并将用户信息保存到数据库中。这是一个简化的示例,实际应用中需要考虑更多安全和错误处理的细节。
评论已关闭