Axios
下载
cnpm install axios
Axios的常用方法
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<button class="get">查询数据</button>
<button class="post">添加数据</button>
<button class="put">修改数据</button>
<button class="delete">删除数据</button>
<script src="/js/axios.min.js"></script>
<script>
document.querySelector(".get").onclick = function(){
//axios的get方法返回一个Promise对象,promise用then来获取数据
axios.get("/fruits").then(res =>{//res是响应的内容
console.log(res.data);//res.data获取响应数据
})
}
document.querySelector(".post").onclick = function(){
axios.post("/fruits",{
fruit:"草莓"//添加草莓进入水果列表
}).then(res =>{
console.log(res.data);
})
}
document.querySelector(".put").onclick = function(){
axios.put("/fruits/1",{//后台是:id 那前台就传一个值如1作为id
fruit:"西瓜"
}).then(res =>{
console.log(res.data);
})
}
document.querySelector(".delete").onclick = function(){
axios.delete("/fruits/0").then(res =>{
console.log(res.data);
})
}
</script>
</body>
</html>
server.js
const Koa = require("koa");
const router = require("koa-router")();
const parser = require("koa-parser");
const nunjucks = require("nunjucks");
const views = require("koa-views");
const static = require("koa-static");
const app = new Koa();
app.use(parser());
app.use(static(__dirname + "/public"));
app.use(views(__dirname + "/views",{
map:{
html:"nunjucks"
}
}));
router.get("/", async ctx =>{
await ctx.render("index");
})
let dataList = ["香蕉","苹果","鸭梨"];
//get查看
router.get("/fruits", ctx =>{
ctx.body = dataList;
});
//post添加
router.post("/fruits", ctx =>{
let fruit = ctx.request.body.fruit;
dataList.push(fruit);
ctx.body = dataList;
});
//put修改
router.put("/fruits/:id", ctx =>{//路由传参:id
let id = ctx.params.id;
let fruit = ctx.request.body.fruit;
dataList.splice(id,1,fruit);
ctx.body = dataList;
});
//delete删除
router.delete("/fruits/:id", ctx =>{
let id = ctx.params.id;
dataList.splice(id,1);
ctx.body = dataList;
});
app.use(router.routes());
app.listen("3000",() => {
console.log("server is running");
});
jQuery的ajax方法
其中 done是获取数据成功之后执行的方法
res是响应数据,对应axios中的res.data