1.再vscode中新建文件夹,右键文件夹选择集成终端中打开
2.输入初始化命令:npm init -y
3.安装express 模块:npm i express
4.安装mysql模块:npm i mysql
const express = require('express') //引入express 模块
const app = express() //创建实例
const mysql = require('mysql') //引入mysql 模块
// 创建数据库连接 填入数据库信息
//填自己数据库的信息!!!!!!!!!!!
const conn = mysql.createConnection({
user:'root', //用户名
password:'root', //密码
host:'localhost', //主机(默认都是local host)
database:'node' //数据库名
})
// 测试连接
conn.connect(err=>{
console.log(err,'如果为null 连接成功');
})
// 定义路由(说白了就是网址)
app.get('/a', (req, res) => {
// let sqlStr = "INSERT INTO user(name, pwd) VALUES ('sansan', '123456');"
// let sqlStr = "update user set name='sisi' where id=5";
let sqlStr = "select * from user where id ";
// let sqlStr = "delete from user where id=5 ";
插入多条数据
// const params =[
// ['小明',"11111"],['小雯',"22222"],['小华',"33333"]
// ];
// conn.query("INSERT INTO user(name, pwd) VALUES ?;",[params],(err, result) => {
// console.log(err, 'sql语句执行成功');
// // console.log(result);
// })// 执行mysql 语句
conn.query(sqlStr, (err, result) => {
console.log(err, 'sql语句执行成功');
console.log(result);
res.json({code: 200, data: result, msg: '成功'})
})
//成功后的页面显示
// res.send('插入成功')
})// 开启服务器
app.listen(3000, () => {
console.log('服务器在3000端口开启。。。。。');
})
报错
报错信息显示为:
{
"code": "ER_NOT_SUPPORTED_AUTH_MODE",
"errno": 1251,
"sqlMessage": "Client does not support authentication protocol requested by server; consider upgrading MySQL client",
"sqlState": "08004",
"fatal": true
}
解决方案:
1、使用管理员运行命令提示符
2、进入到mysql安装目录的bin目录下默认安装路径大概是(C:\Program Files\MySQL\MySQL Server 8.0\bin)
3、在命令提示行中键入: mysql -u root -p
4、mysql> alter user 'root'@'localhost' identified with mysql_native_password by 'asd123456';此时得到提示Query OK, 0 rows affected (0.01 sec),这里是修改密码的认证方式
5、mysql> flush privileges;此时得到提示Query OK, 0 rows affected (0.01 sec),这里是重启权限
6、mysql> exit 退出mysql
npm install jsonwebtoken express-jwt
jsonwebtoken 用于生成 JWT 字符串 express-jwt 用于将 JWT 字符串解析还原成 JSON 对象
// 1.导入用于生成 JWT 字符串的包
const jwt = require( 'jsonwebtoken' )
// 2.导入用于将客户端发送过来的 JWT 字符串,解析还原成 JSON 对象的包4
const expressJwT = require( 'express-jwt')
const secretKey = "itheima NO1";
调用jsonwebtoken 包提供的 sign() 方法,将用户的信息加密成JWT 字符串,响应给客户端:
const tokenStr = jwt.sign({ username: userinfo.username }, secretKey, { expiresIn: '24h' });
// 用于JWT身份验证的中间件
app.use(expressJwt({ secret: secretKey }).unless({ path: [/^\/api\//] }));
unless的意思是除了api开头的url
客户端每次在访问那些有权限接口的时候,都需要主动通过请求头中的 Authorization 字段,将 Token 字符串发送到服务器进行身份认证。
const express = require('express');
const app = express();
const mysql = require('mysql');
const jwt = require('jsonwebtoken');
const expressJwt = require('express-jwt');
const bodyParser = require("body-parser");
// const secretKey = process.env.SECRET_KEY || "defaultSecretKey";
const secretKey = "itheima NO1";
const dbConfig = {
user: process.env.DB_USER || 'root',
password: process.env.DB_PASSWORD || 'root',
host: process.env.DB_HOST || 'localhost',
database: process.env.DB_DATABASE || 'node',
};const conn = mysql.createConnection(dbConfig);
app.use(bodyParser.urlencoded({ extended: false }))
app.use(bodyParser.json())
// 用于JWT身份验证的中间件
app.use(expressJwt({ secret: secretKey }).unless({ path: [/^\/api\//] }));// 登录端点
app.post('/api/login', async (req, res) => {
try {
const userinfo = req.body;
console.log(userinfo);
const tokenStr = jwt.sign({ username: userinfo.username }, secretKey, { expiresIn: '24h' });
if (userinfo.username !== 'admin' || userinfo.password !== '000000') {
return res.status(400).json({ status: 400, message: "登录失败" });
}// 登录成功
res.json({ status: 200, message: "登录成功", token: tokenStr });
} catch (error) {
console.error(error);
res.status(500).json({ status: 500, message: "内部服务器错误" });
}
});// 保护的端点,用于获取用户信息
// Protected endpoint to get user info
app.get('/admin/getinfo', (req, res) => {
// 检查 req.user 是否存在
if (req.user && req.user.username) {
res.json({ status: 200, message: "获取用户信息成功", data: req.user });
} else {
res.status(401).json({ status: 401, message: "未授权访问" });
}
});
// 数据库连接
conn.connect((err) => {
if (err) {
console.error('连接数据库时发生错误:', err);
process.exit(1); // 如果无法连接到数据库,则退出应用程序
} else {
console.log('已连接到数据库');
// 在成功连接到数据库后启动服务器
app.listen(3000, () => {
console.log('服务器正在端口3000上运行');
});
}
});
const mysql = require('mysql');
const express = require('express');
const app = express();
const interface = require('./interface');
const bodyParser = require("body-parser");// 连接数据库
const conn = mysql.createConnection({
user: 'root',
password: 'root',
port: 3306,
host: 'localhost',
database: 'node'
});// 解析请求体
app.use(express.json());app.use(bodyParser.urlencoded({ extended: false }))
app.use(bodyParser.json())
// 测试连接
conn.connect(err => {
console.log(err, '连接成功');
});
// 获取用户列表
app.get('/getList', (req, res, next) => {
// sql语句查询列表所有数据 SELECT * FROM 你数据库的表名,我这里是users
let sql = "SELECT * FROM users where id=1";
conn.query(sql, (err, r) => {
res.json({code: 200, data: r, msg: '成功'})
})
});
// 添加用户接口
app.post('/addUser', async (req, res) => {
try {
await interface.addUser(conn, req, res);
} catch (error) {
console.error(error);
res.status(500).json({ code: 500, data: null, msg: '内部服务器错误' });
}
});
// 修改用户接口
app.post('/updateUser', (req, res) => {
interface.updateUser(conn, req, res)
})// 删除用户接口
app.post('/deleteUser', (req, res) => {
interface.deleteUser(conn, req, res)
})
// 开启服务器
const PORT = 3000;
app.listen(PORT, () => {
console.log(`服务器在${PORT}端口开启。。。。。`);
});
// 新增
const addUser = async (conn, req, res) => {
const params = req.body;
const ret = {};if (!params.user) {
ret.code = 501;
ret.data = null;
ret.msg = '请传递用户名';
res.json(ret);
return;
} else if (!params.pass) {
ret.code = 501;
ret.data = null;
ret.msg = '请设置用户密码';
res.json(ret);
return;
}try {
const results = await queryAsync(conn, 'INSERT INTO users(user,pass) VALUES (?, ?)', [params.user, params.pass]);if (results.affectedRows === 0) {
ret.code = 501;
ret.message = '请传递正确的参数';
} else {
ret.code = 200;
ret.data = null;
ret.msg = '添加成功';
}
res.json(ret);
} catch (error) {
console.error(error);
throw error;
}
};const queryAsync = (conn, sql, values) => {
return new Promise((resolve, reject) => {
conn.query(sql, values, (error, results, fields) => {
if (error) {
reject(error);
return;
}
resolve(results);
});
});
};
// 修改用户
const updateUser = (conn, req, res) => {
const params = req.body
// console.log(params);
const ret = {}
if (params.user == '') {
ret.code = 501
ret.data = null
ret.msg = '请传递用户名'
res.json(ret)
return
} else if (params.pass == '') {
ret.code = 501
ret.data = null
ret.msg = '请设置用户密码'
res.json(ret)
return
} else if (params.id == '') {
ret.code = 501
ret.data = null
ret.msg = '请传递用户id'
res.json(ret)
return
} else {
conn.query(`UPDATE users SET
user="${params.user}",
pass="${params.pass}" WHERE id="${params.id}"`,
function (error, results, fields) {
if (error) {
ret.code = 500
ret.data = null
ret.msg = error.sqlMessage
return
}
if (results.length === 0) {
ret.code = 501
ret.message = '请传递正确的参数'
} else {
ret.code = 200
ret.data = null
ret.msg = '修改成功'
}
res.json(ret)
})
}
}// 删除用户
const deleteUser = (conn, req, res) => {
const params = req.body
// console.log(params);
const ret = {}
if (params.id == '') {
ret.code = 501
ret.data = null
ret.msg = '请传递用户id'
res.json(ret)
return
} else {
conn.query(`DELETE FROM users WHERE id="${params.id}";`,
function (error, results, fields) {
// console.log(error);
if (error) {
ret.code = 500
ret.data = null
ret.msg = error.sqlMessage
return
}
if (results.length === 0) {
ret.code = 501
ret.message = '请传递正确的参数'
} else {
ret.code = 200
ret.data = null
ret.msg = '删除成功'
}
res.json(ret)
})
}
}// 最后 exports
exports.addUser = addUser;
exports.updateUser = updateUser;
exports.deleteUser = deleteUser