async function run(){
const koa = require('koa')
const Router = require('koa-router')
const Static = require('koa-static-cache')
const mysql=require('mysql2/promise')
const bodyparser=require('koa-bodyparser')
const koaBody=require('koa-body')
const multiparty=require('koa2-multiparty')
const path=require('path')
const fs=require('fs')
const app = new koa()
const router = new Router()
app.use(async (ctx, next)=> {
ctx.set('Access-Control-Allow-Origin', '*');
ctx.set('Access-Control-Allow-Headers', 'Content-Type, Content-Length, Authorization, Accept, X-Requested-With , yourHeaderFeild');
ctx.set('Access-Control-Allow-Methods', 'PUT, POST, GET, DELETE, OPTIONS');
if (ctx.method == 'OPTIONS') {
ctx.body = 200;
} else {
await next();
}
});
app.use(bodyparser())
//文件上传
app.use(koaBody({
multiparty:true,
encoding:'gzip',
formidable:{
maxFieldsSize:20*1024*1024,//设置文件上传最大大小
},
keepExtensions:true //保存后缀
}))
app.use(
Static('./static'), {
prefix: '/static',
gzip: true
}
)
//连接数据库
const connection=await mysql.createConnection({
host:"127.0.0.1",
user:"uniapp",
password:'123456',
database:'uniapp'
})
// router.get('/test',async ctx=>{
// // ctx.body='hello'
// let [data]=await connection.query("SELECT * FROM videos")
// ctx.body=data
// })
//文件上传接口
router.post('/upload',multiparty(),async ctx=>{
//获取formdata中的数据
const {name,type}=ctx.req.body
//文件名及文件路径
const file=ctx.req.files.file
const path=ctx.req.files.file.path
//创建文件的输入流
const fileReader=fs.createReadStream(path)
//定义文件存储路径
const fileDir=`${__dirname}/static/${type}`
const filepath=`${fileDir}/${name}`
//创建文件输出流
const fileWrite=fs.createWriteStream(filepath)
//写入文件数据
fileReader.pipe(fileWrite)
ctx.body={
code:1,
data:'上传成功'
}
})
router.get('/video',async ctx=>{
let [data]=await connection.query("SELECT * FROM videos LIMIT 0,3")
ctx.body={
code:1,
data
}
})
//通过id查询用户信息接口
router.get('/user',async ctx=>{
let [data]=await connection.query("SELECT * FROM user WHERE id=1")
ctx.body={
code:1,
data
}
})
//修改用户信息接口
router.post('/user',async ctx=>{
const {data,columnName}=ctx.request.body
let query=""
switch (columnName){
case userName:query="UPDATE user SET userName =? WHERE id=1";
break;
case userId:query="UPDATE user SET userId =? WHERE id=1";
break;
case redirect:query="UPDATE user SET redirect =? WHERE id=1";
break;
case school:query="UPDATE user SET school =? WHERE id=1";
break;
case sex:query="UPDATE user SET sex =? WHERE id=1";
break;
case birthday:query="UPDATE user SET birthday =? WHERE id=1";
break;
case city :query="UPDATE user SET city =? WHERE id=1";
break;
default:
ctx.body='错误'
}
// let query="UPDATE user SET userName =? WHERE id=1"
value=[data]
let [lr]=await connection.query(query,value)
if(lr.affectedRows>0){
ctx.body={
code:1,
data:'成功'
}
}else{
ctx.body={
code:0,
data:'失败'
}
}
})
app.use(router.routes())
app.listen(8080)
}
run()