node.js,mysql写登录注册,不用express
时间: 2023-06-10 18:06:05 浏览: 56
首先,需要安装 mysql 和 mysql2 模块,可以使用以下命令进行安装:
```
npm install mysql mysql2
```
接下来,可以使用以下代码进行登录和注册功能的实现:
```js
const mysql = require('mysql2');
// 创建数据库连接
const connection = mysql.createConnection({
host: 'localhost',
user: 'root',
password: 'password',
database: 'test'
});
// 连接数据库
connection.connect((err) => {
if (err) throw err;
console.log('Connected to database');
});
// 注册功能实现
function register(username, password) {
return new Promise((resolve, reject) => {
// 检查用户名是否已存在
connection.query('SELECT * FROM users WHERE username = ?', [username], (err, results) => {
if (err) reject(err);
if (results.length > 0) {
reject(new Error('Username already exists'));
} else {
// 插入新用户
connection.query('INSERT INTO users (username, password) VALUES (?, ?)', [username, password], (err, results) => {
if (err) reject(err);
resolve('User registered');
});
}
});
});
}
// 登录功能实现
function login(username, password) {
return new Promise((resolve, reject) => {
// 查询用户信息
connection.query('SELECT * FROM users WHERE username = ?', [username], (err, results) => {
if (err) reject(err);
if (results.length > 0) {
// 比较密码是否匹配
if (results[0].password === password) {
resolve('Login successful');
} else {
reject(new Error('Incorrect password'));
}
} else {
reject(new Error('User not found'));
}
});
});
}
// 使用示例
register('testuser', 'testpassword')
.then((message) => {
console.log(message);
return login('testuser', 'testpassword');
})
.then((message) => {
console.log(message);
})
.catch((err) => {
console.error(err);
});
```
需要注意的是,上述代码中使用了 Promise 进行异步操作的处理。同时,为了简化代码,密码并没有进行加密处理,实际使用时需要进行加密存储和比对。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)