/*
koa-router 路由
var Swig=require('koa-swig') swig 模板
var co=require('co')
koa-bodyparser 处理POST请求参数
koa-static-cache 静态文件
var fs=require('fs') node 自带
mysql2
*/
(async function(){
const mysql=require('mysql2/promise')
const koa=require('koa')
const Static=require('koa-static-cache')
const Router=require('koa-router')
const bodyParser = require('koa-bodyparser')
const fs=require('fs')
const app=new koa()
const router=new Router()
app.use(bodyParser())
app.use(Static('./static',{
prefix:'/static',
gzip:true
}))
const connection=await mysql.createConnection({
host:'localhost',
user:'root',
password:'root',
database:'test'
})
let arr=await connection.query('SELECT * FROM todolist')
// console.log(arr);
const content=fs.readFileSync('./static/index.html')
router.get('/list',async ctx=>{
let [arr]=await connect.query('SELECT * FROM todolist')
ctx.body={
code:0,
data:arr
}
})
router.post('/add',async(ctx,next)=>{
const {name,price,number}=ctx.request.body
let [data]=await connection.query("INSERT INTO todolist (name,price,number) VALUES ("+name+","+price+","+number+")")
if(data.affectedRows>0){
ctx.body={
code:0,
msg:"添加成功"
}
}else{
ctx.body={
code:1,
msg:"添加失败"
}
}
})
router.post('/change',async(ctx,next)=>{
const {name,price,number}=ctx.request.body
let query="UPDATE todolist SET name=?,price=?,number=? WHERR id=?"
const value=[id,name,price,number]
let [data]=await connection.query(query,value)
if(data.affectedRows>0){
ctx.body={
code:0,
msg:"修改成功"
}
}else{
ctx.body={
code:1,
msg:"修改失败"
}
}
})
router.post('/remove',async ctx=>{
const id=ctx.request.body.id
let query="DELETE FROM todolist WHERE id=?"
const value=id
let [data]=await connection.query(query,value)
if(data.affectedRows>0){
ctx.body={
code:0,
msg:"删除成功"
}
}else{
ctx.body={
code:1,
msg:"删除失败"
}
}
})
app.use(router.routes())
app.listen(8080)
})()