一、Axios
- Axios 是一个基于 promise 的 HTTP 库,可以用在浏览器和 node.js 中。
- 支持Promise
- 能够拦截请求和响应
- 自动转换JSON数据
- 能转换请求和响应数据
1.1、Axios的基础用法
- get 和 delete 请求传递数据
- 通过传统url 以 ? 的形式传递参数
- restful (get查询, post新增, put更新, delete删除)
- 通过 params 形式传递参数
- post 和put 请求传递参数
- 通过选项传递参数
- 通过 URLSearchParams 传递参数
axios.get('http://10.176.135.77:8088/index/cats').then((res) =>{ this.list = res.data.data.filter((res) => { res.type = res.type == 1 ? '一级分类': res.type == 2 ? '二级分类': '三级分类' return res })})
1.2、全局配置
// 配置公共的请求地址axios.defaults.baseURL = "http://127.0.0.1:8088/"// 配置超时时间axios.defaults.timeout = 2000// 配置公共的请求头的token校验axios.defaults.headers.common['Authorization'] = AUTH_TOKEN// 配置公共的 post 的 Content-Typeaxios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded'
1.3、Axios 拦截器
// 请求拦截axios.interceptors.request.use(config => { config.headers.Authorization = window.sessionStorage.getItem("token") return config})// 响应拦截axios.interceptors.response.use(config => { config.headers.Authorization = window.sessionStorage.getItem("token") return config})