MySQL数据库和前端的连接

const Koa = require("koa");
const Router = require("koa-router");
const static = require("koa-static")
const views = require("koa-views");
const mysql2 = require("mysql2");

let app = new Koa();
let router = new Router();

app.use(static(__dirname + "/static"));
app.use(views(__dirname + "/views", {
    extension: 'pug'
}));

// 配置和数据库之间的连接
const connection = mysql2.createConnection({
    host: "localhost",
    user: "root",
    password: "123321",
    database: "js01",
    charset: "utf8"
});

router.get("/", async ctx => {
    ctx.redirect("/index")
})
router.get("/index", async ctx => {
    let mydata;
    let sql = "SELECT * FROM sb WHERE age>1";

    try {
        let [rows, fields] = await connection.promise().query(sql);
        mydata = rows;
    } catch (err) {
        console.log(s);
    }
    
    await ctx.render("index", {
        mydata
    })
})

app.use(router.routes());
app.listen(8080);

你可能感兴趣的:(MySQL数据库和前端的连接)