目录
一、axios定义和特点
定义:一款axios请求工具。Axios是一个基于promise的HTTP库,类似于jQuery的ajax,用于http请求。可以应用于浏览器端和node.js,既可以用于客户端,也可以用于node.js编写的服务端。
特点:
- 01前后端都可以使用
- 02不依赖dom
- 03拦截扩展强调
- 04可封装复用性强
二、安装
1、cd到项目目录
2、npm i axios -S
![]()
三、 在vue全局挂载
01导入main.js(没有./) import axios from 'axios'
02挂载到vue全局(原型上),每个组件都能使用 vue.prototype.$axios = axios;
03使用 this.$axios.xxx
四、方法
基础方法:
axios({ url,//请求的地址 method,// 请求方法 get,post,put,delete data,//post请求的数据 params,//get请求的数据 headers,//请求头配置 })
便捷方法:
post(url,data,config) get(url,config) get传递参数给后端 ?参数名=参数值&参数名2=参数值2 ?current=2 .delete(url,config) 删除 .put(url,data,config) 修改
get方法
方法一
axios.get("/data.json", { params: { id: 12 } }) // 网络请求成功 .then(res => { console.log(res); }) // 网络请求失败 .catch(err => { console.log(err); });
方法二
axios({ method: "get", url: "/data.json", params:{ id:12 } }).then(res => { console.log(res); });
带有参数后get请求实际是http://xxxxx/data.json?id=12,写了这么多结果就是url加了参数。
五、执行结果
网络请求成功
.then(res=>{
res.data 请求返回的数据
})请求失败
.catch(err=>{
err.response.data 返回失败数据
})
六、config的axios配置
方法一:
//直接在App.vue文件中配置 this.$axios.get( "http://dida100.com:8888/api/feed?current=" + this.current, { headers: { "Authorization": 'Bearer ' + localStorage.getItem("token") } }, )
方法二:
//指定默认的请求域名 axios.defaults.baseURL = "http://dida100.com:8888" //给每个请求拦截一下,添加请求Token信息 axios.interceptors.request.use(function(config) { config.headers.Authorization = 'Bearer ' + localStorage.getItem("token") return config })
- interceptors 拦截器
- request 请求
- config 配置
- headers 头信息
- Authorization 权限
- defaults 默认
- baseURL 基础URL
七、 restFul
RESTful是一种常见的REST应用,是遵循REST风格的web服务,REST式的web服务是一种ROA(面向资源的架构)。
- 1. 接口设计风格
- 2. 强调每个url地址都是一个资源
- 3. 可以通过get ,post,put,delete操作资源
- 4. get获取,post新增,put修改,delete删除