确保已安装node
创建项目文件夹,并初始化
npm init -y
安装express
?npm install express
安装mysql
npm install mysql
安装body-parser
npm install body-parser
新建db/mysql.js
const mysql = require('mysql');
let db = mysql.createConnection({
host: '127.0.0.1',
user: 'root',
password: '123456',
database: 'demo_data',
port: 3306
});
db.connect(function (err) {
if (err) {
console.log("err" + err.stack);
return;
}
console.log("connection id " + db.threadId);
});
module.exports = db;
新建 app.js
const express = require('express');
const app = new express();
const db = require('./db/mysql');
const bodyParser = require('body-parser');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));
app.use(express.static(__dirname + '/'));
app.listen(3002, () => {
console.log('服务已启动, 监听端口是 3002');
});
// 查询所有用户和密码
app.get('/api/user', (req, res) => {
const sqlStr = 'SELECT * FROM sys_user;'
db.query(sqlStr, (err, results) => {
// 查询数据失败
if (err) {
return console.log(err.message)
} else {
res.send({
status: 200,
message: '获取所有用户成功',
data: results,
})
}
})
})
module.exports = app;
目录结构如下:
启动服务:
node app.js
测试服务:
?