目录
数据库
写一个js用来配置
const express = require('express');
const bodyParser = require('body-parser');
const server = express();
/**
* 配置跨域请求头
*/
server.all('*', function(req, res, next) {
// res.header('Access-Control-Allow-Origin', '*');
res.header("Access-Control-Allow-Origin", req.headers.origin);
res.header('Access-Control-Allow-Headers', 'Content-Type, Content-Length, Authorization, Accept, X-Requested-With , header');
res.header('Access-Control-Allow-Methods', 'PUT, POST, GET, DELETE, OPTIONS');
res.header("Access-Control-Allow-Credentials",true);
if (req.method == 'OPTIONS') {
res.send(200);
/make the require of options turn back quickly/
} else {
next();
}
});
//监听端口
server.listen(3333, () => {
console.log("正在监听3333端口");
});
server.use('/', require('./route/index.js')());
写一个server用来写接口
const express = require('express');
const mysql = require('mysql');
const db = mysql.createPool({
host: 'localhost', // db host
user: 'root', // db user
password: 'root', //db pwd
database: 'testserver' // db name
});
module.exports = () => {
// const route = express.Router(); //创建路由路径的链式路由句柄。
const route = express();
//配置post请求 获取到body
const bodyParser = require('body-parser');
route.use(bodyParser.urlencoded({ extended: false }));
route.use(bodyParser.json());
/**
* 增加
*/
route.post("/addUser", (req, res) => {
let params = req.body;
const insertUserInfo =`INSERT INTO userinfo(name, age, sex) VALUES('${params.name}', '${params.age}', '${params.sex}')`;
db.query(insertUserInfo, (err, data) => {
if(err){
res.send({"msg": "数据库错误", "code": "500"})
}else{
if(data.length!==0){
res.send({"msg": "添加成功", "code": "200"})
}
}
})
});
/**
* 删除
*/
route.get("/delUser", (req, res) => {
let userId = req.query.id;
const delUsers = `DELETE FROM userinfo WHERE ID = '${userId}'`;
db.query(delUsers, (err, data) => {
if(err){
res.send({"msg": "数据库错误", "code": "500"})
}else{
if(data.length!==0){
res.send({"msg": "删除成功", "code": "200"})
}
}
})
});
/**
* 修改
*/
route.post("/updateUser", (req, res) => {
let users = req.body;
const updateUsers = `UPDATE userinfo SET name = '${users.name}', age = '${users.age}', sex = '${users.age}' WHERE id = '${users.id}'`;
db.query(updateUsers, (err, data) => {
if(err){
res.send({"msg": "数据库错误", "code": "500"})
}else{
if(data.length!==0){
res.send({"msg": "修改成功", "code": "200", data: data})
}
}
})
});
/**
* 查询
*/
route.get("/selectUser", (req, res) => {
let userId = req.query.id;
let selectUsers = `SELECT * FROM userinfo WHERE id = '${userId}'`;
if(!userId){
selectUsers = `SELECT * FROM userinfo`;
}
db.query(selectUsers, (err, data) => {
if(err){
res.send({"msg": "数据库错误", "code": "500"})
}else{
if(data.length!==0){
res.send({"msg": "查询成功", "code": "200", data: data})
}
}
})
});
return route;
};
结果
增
删
改
查