首先来说一下axios的作用: axios主要是用来发送请求(请求库)
vue中安装命令: npm install axios 或 yarn add axios
在所用到的文件中引入: import axios from "axios";
官网: http://www.axios-js.com
特点: 支持客户端发送Ajax请求
支持服务端Node.js发送请求
支持Promise相关用法
支持请求和响应的拦截器功能
* 自动转换JSON数据
( 此处因为会返回promise对象,promise解决异步 =>> .then 或 async await)
axios({
methods:'请求方式' , // get post
url:'请求地址',
data:{
xxx:xxx //拼接请求体的参数,post请求的参数
},
params: {
xxx:xxx // 拼接到请求行的参数,get请求的参数
}
}).then(res => {
console.log(res.data) // 后台返回的结果
}).catch(err => {
console.log(err) // 后台报错的返回
})
什么是ajax?
一种前端请求异步请求后端的技术
ajax原理?
浏览器window接口的XMLHttpRequest
全局默认配置基地址的格式:axios.defaults.baseURL="不变的基地址"
上个小案例:
(可以粘贴到编辑器里引入运行一下)
<template>
<div>
<p>1.获取所有图书信息</p>
<button @click="getAllFn">点击-查看控制台</button>
<p>2.查询某本书籍信息</p>
<input type="text" placeholder="请输入要查的书名" v-model="bName" />
<button @click="findFn">查询</button>
<p>3.新增图书信息</p>
<div>
<input type="text" placeholder="书名" v-model="bookObj.bookname">
<input type="text" placeholder="作者" v-model="bookObj.author">
<input type="text" placeholder="出版社" v-model="bookObj.publisher">
<button @click="sendFn">发布</button>
</div>
</div>
</template>
<script>
// 目标1:获取所有的图书信息
// 1. 下载axios
// 2. 引入axios
// 4.全局配置
axios.defaults.baseURL="http://123.57.109.30:3006"
import axios from "axios";
export default {
data() {
return {
bName: "",
// 新增
bookObj:{
bookname:'',
author:'',
publisher:'',
}
};
},
methods: {
// 获取所有图书信息
getAllFn() {
// 3.发起axios请求
axios({
url: "/api/getbooks",
// methods 可以定义多个 method 只能定义一个
// 默认就是GET请求,可以省略不写
method: "GET",
}).then((res) => {
console.log(res);
});
},
// 查询
findFn() {
axios({
url: "/api/getbooks",
method: "GET",
params: {
// 在params里写的都会被axios最终拼接到url?后面
bookname: this.bName
},
}).then(res => {
console.log(res)
});
},
// 新增
sendFn() {
axios({
url: "/api/addbook",
method:"POST",
data: {
appkey: "7250d3eb-18e1-41bc-8bb2-11483665535a",
// ...this.bookObj
// 等同于下面
bookname:this.bookObj.bookname,
author: this.bookObj.author,
publisher:this.bookObj.publisher,
}
}).then(res=> {
console.log(res)
})
}
},
};
</script>
<style>
</style>