一、Axios

  • Axios 是一个基于 promise 的 HTTP 库,可以用在浏览器和 node.js 中。
  • 支持Promise
  • 能够拦截请求和响应
  • 自动转换JSON数据
  • 能转换请求和响应数据

1.1、Axios的基础用法

  • get 和 delete 请求传递数据
    • 通过传统url 以 ? 的形式传递参数
    • restful (get查询, post新增, put更新, delete删除)
    • 通过 params 形式传递参数
  • post 和put 请求传递参数
    • 通过选项传递参数
    • 通过 URLSearchParams 传递参数
  1. axios.get('http://10.176.135.77:8088/index/cats').then((res) =>{
  2. this.list = res.data.data.filter((res) => {
  3. res.type = res.type == 1 ? '一级分类': res.type == 2 ? '二级分类': '三级分类'
  4. return res
  5. })
  6. })

1.2、全局配置

  1. // 配置公共的请求地址
  2. axios.defaults.baseURL = "http://127.0.0.1:8088/"
  3. // 配置超时时间
  4. axios.defaults.timeout = 2000
  5. // 配置公共的请求头的token校验
  6. axios.defaults.headers.common['Authorization'] = AUTH_TOKEN
  7. // 配置公共的 post 的 Content-Type
  8. axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded'

1.3、Axios 拦截器

  1. // 请求拦截
  2. axios.interceptors.request.use(config => {
  3. config.headers.Authorization = window.sessionStorage.getItem("token")
  4. return config
  5. })
  6. // 响应拦截
  7. axios.interceptors.response.use(config => {
  8. config.headers.Authorization = window.sessionStorage.getItem("token")
  9. return config
  10. })