Node.js-搭建自己的服务器(仿egg.js)

1、项目目录

                               Node.js-搭建自己的服务器(仿egg.js)_第1张图片

2、index.js

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);

3、router.js

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;
}

4、route.js

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);
        })
    }
}

5、mysqldbtool.js

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();
}

6、service.js

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);
    }
}

7、index.html

 

你可能感兴趣的:(nodejs,javascript)