1.定义
一款支持前后端的网络请求工具
特点:
01:前后端都可以使用,主要用在项目未上线之前的网络测试02:不依赖dom
03:拦截扩展强调
04:可封装复用性强
2.安装:(前提是安装node.js)
cd 项目目录
npm i axios -S
3.在vue全局挂载
01:导入main.js
import axios from ‘axios’
02 挂载
Vue.prototype.$axios = axios;
//挂载到vue全局(原型上),在每个组件上都能使用
03 在每个.vue文件中都可以使用
this.$axios.xxx
4.主要用法
this.$axios.post(url,data,config)
this.$axios.get(url,config)
get传递参数给后端
?参数名=参数值&参数名2=参数值2
?current=2this.$axios.delete(url,config)
删除this.$axios.put(url,data,config)
修改
或者写成另一种形式
axios({
url:" ",//请求的地址
method:" ",// 请求方法 get,post,put,delete
data:{ },//post请求的数据
params:{},//get请求的数据
headers:{},//请求头配置
返回
网络请求成功
this.$axios({...}).then(res=>{
res.data 请求返回的数据
})请求失败
.catch(err=>{
err.response.data 返回失败数据
})
5.axios配置拦截器
axios.defaults.baseURL='http://xxxxxx.com:8888';
请求的url会自动拼接上http://xxxxxx.com:8888
axios.interceptors.request.use(function(config){
config.headers.Authorization="Bearer "+localStorage.getItem("token")
return config
})配置一些token信息,每个请求都生效,就不用手动在请求头中配置了
6.restFul(一种设计风格,代码思想)
1. 接口设计风格
2. 强调每个url地址都是一个资源
3. 可以通过get ,post,put,delete操作资源
4. get获取,post新增,put修改,delete删除