node + express 学生信息管理
api/db.js
const mysql = require("mysql");
const connection = mysql.createConnection({
host: "localhost",
user: "root",
password: "123456",
database: "school2",
});
connection.connect();
// 根据登录和密码查询用户信息
module.exports.selectByNameAndPwd = function (loginName, pwd, callback) {
var sql = `select * from student where LoginName='${
loginName}' and LoginPwd='${
pwd}'`;
connection.query(sql, function (err, data) {
if (err) {
callback(err);
} else {
callback(data);
}
});
};
// 根据用户姓名或登录名查询用户信息
module.exports.selectByCondtion = function (name, callback) {
var sql = `select * from student where Sname like '%${
name}%' or LoginName like '%${
name}%'`;
connection.query(sql, function (err, data) {
if (err) {
callback(err);
} else {
callback(data);
}
});
};
// 根据用户Sno删除用户信息
module.exports.deleteBySno = function (sno, callback) {
var sql = `delete from student where Sno='${
sno}'`;
connection.query(sql, function (err, data) {
if (err) {
callback(err);
} else {
callback(data);
}
});
};
// 根据Sno查询用户信息
module.exports.selectBySno = function (sno, callback) {
var sql = `select * from student where Sno = '${
sno}'`;
connection.query(sql, function (err, data) {
if (err) {
callback(err);
} else {
callback(data);
}
});
};
// 根据用户Sno编辑用户信息和新增用户信息
module.exports.addAndUpdateBySno = function (sno, student, callback) {
if (sno == -1) {
var sql = `insert into student values('${
student.Sno}','${
student.Sname}',${
student.Sage},'${
student.Ssex}','${
student.loginName}','${
student.loginPwd}')`;
} else {
sql = `update student set Sno='${
student.Sno}',Sname='${
student.Sname}',Sage=${
student.Sage},Ssex='${
student.Ssex}',LoginName='${
student.loginName}',LoginPwd='${
student.loginPwd}' where Sno='${
sno}'`;
}
connection.query(sql, function (err, data) {
if (err) {
callback(err);
} else {
callback(data);
}
});
};
api/http.js
const express = require("express");
const app = new express();
const cors = require("cors");
const db = require("./db");
app.use(cors());
app.all("*", function (req, res, next) {
res.setHeader("Access-Control-Allow-Origin", "*");
next();
});
// 根据登录和密码查询用户信息
app.get("/student/selectByNameAndPwd", function (req, res) {
db.selectByNameAndPwd(
req.query.loginName,
req.query.loginPwd,
function (data) {
if (data.length > 0) {
res.json({
status: 1, msg: "登录成功", data: data });
} else {
res.json({
status: 0, msg: "登录失败", data: data });
}
}
);
});
// 根据用户姓名或登录名查询用户信息
app.get("/student/selectByCondtion", function (