let http =require("http");
let router = require("./router/router.js")
let app = http.createServer((req,res)=>{
router(req,res);
})
app.listen(81);
//配置路由
router.use("/mysqldata",router.route.mysqldata);
router.use("/mysqldata2",router.route.mysqldata2);
let fs = require("fs"); // fs模块,读取文件
let url = require("url"); //url模块,解析url
let querystring = require("querystring") //querystring模块,解析参数
let route = require("./route.js");
module.exports = function(req, res) {
let pathname = url.parse(req.url).pathname.substr(1);
req.query = querystring.parse(url.parse(req.url).query);
res.json = (arg) => { //利用回调函数从后端传入对象过来,并转化为json数据,再传给前端
res.end(JSON.stringify(arg));
}
if (module.exports.route[pathname]) {
//数据接口的路由
module.exports.route[pathname](req, res);
} else {
//静态资源的托管
fs.readFile(__dirname + "/../src/" + pathname, (err, data) => {
res.end(data);
})
}
}
module.exports.route = { ...route};
module.exports.use = function(pathname, callback) {
module.exports.route[pathname.substr(1)] = callback;
}
let service = require("../service/service.js")
module.exports = {
mysqldata(req, res) {
service.getAllformTable("student", (error, results, fields) => {
// console.log(results)
res.json(results)
})
},
mysqldata2(req, res) {
service.addtoDB(req.query, (error, results, fields) => {
if (error) {
res.json(error);
}
res.json(results);
})
}
}
let mysql = require("mysql");
module.exports = function(option, sql, callback) {
//配置信息
let connection = mysql.createConnection(option);
//连接mysql
connection.connect();
//操作mysql
connection.query(sql, (error, results, fields) => {
callback(error, results, fields);
})
//断开mysql连接
connection.end();
}
let mysqldbtool = require("./mysqldbtool.js");
let option = {
host: 'localhost',
user: 'root',
password: 'root',
database: 'h52001'
}
module.exports = {
//获取数据库中所有数据
getAllformTable(tablename, callback) {
let sql = `select * from ${tablename}`;
mysqldbtool(option, sql,callback);
},
//添加数据到数据库
addtoDB(userdata, callback) {
let sql = `insert into student(name,birth,sex,description) values("${userdata.name}","${userdata.birth}","${userdata.sex}","${userdata.description}")`;
mysqldbtool(option, sql,callback);
}
}