vue2 通过 axios 访问koa2,从mysql 拿到数据更新vue2中的内容
axios 类似ajax
注意红色字体
node --inspect index.js (启用debug模式)
node index.js (正常模式)
------index.js----
const Koa = require('koa')
const app = new Koa()
const views = require('koa-views')
const path = require('path')
// 加载模板引擎
app.use(views(path.join(__dirname, './view'), {
extension: 'ejs'
//换成这个之后,可以在html中用ejs的语法, map : {html:'ejs'}
}))
const Router = require('koa-router')
let home = new Router()
// mysql access [1]
const dbprocess = require('./async-db')
const cors = require('koa2-cors');
app.use(cors({
exposeHeaders: ['WWW-Authenticate', 'Server-Authorization', 'Date'],
maxAge: 100,
credentials: true,
allowMethods: ['GET', 'POST', 'OPTIONS'],
allowHeaders: ['Content-Type', 'Authorization', 'Accept', 'X-Custom-Header', 'anonymous'],
}));
// 子路由1
home.get('/', async ( ctx )=>{
let html = `
<ul>
<li><a href="/page/helloworld">/view/helloworld</a></li>
<li><a href="/page/404">/view/404</a></li>
<li><a href="/page/delete">/view/delete</a></li>
</ul>
`
//ctx.body = html
let xxx={name:'abc',age:30,address:'xi\'an'}
ctx.body=xxx
}).get('/all', async ( ctx )=>{
let peoples= await dbprocess.selectAllData()
.then(m => {
console.log("~~~ get all data");
return m
})
ctx.body=peoples
})
// 子路由2
let page = new Router()
page.get('/404', async ( ctx )=>{
ctx.body = '404 page!'
}).get('/helloworld', async ( ctx )=>{
/*
//单条查询
let res,title='abc',
id ,
name ,
age ,
address ,
salary ;
await dbprocess.findUserData([1])
.then(x => {
res=x
//console.log(res[0])
})
await ctx.render('userejs', {
title,
id:res[0]['id'],
name:res[0]['name'],
age:res[0]['age'],
address:res[0]['address'],
salary:res[0]['salary']
})
*/
// 多条查询
let alluser,allusers,title;
allusers=await selectAllData()
console.log(allusers)
await ctx.render('userejs', {
title:12345,
id:1,
name:2,
age:3,
address:4,
salary:5,
alluser:allusers
})
}).get('/delete', async ( ctx )=>{
//http://localhost:3000/page/delete?id=2
let ctx_query = ctx.query
let ctx_querystring = ctx.querystring
let ar=ctx_querystring.split("=")
if(ar[0]==='id'){
//ctx.body=ar[1]
await dbprocess.deleteUserData(ar[1])
.then(z => {