vue基础-axios详解

1.1 背景

Axios 是一个基于 promise 的 HTTP 库,可以用在浏览器和 node.js 中, 也是 vue 官方推荐使用的 http 库;封装axios,一方面为了以后维护方便,另一方面也可以对请求进行自定义处理。

1.2 vue请求模块选择

在这里插入图片描述

2 应用

2.1 安装axios依赖

npm install axios --save

2.2 GET 方法

📌1、引用axios模块

import axios from "axios";

📌2、get请求

<template>
  <div>
    <button @click="send">发送get</button>
    <br />
    {{info}}
  </div>
</template>

<script>
import axios from "axios";

export default {
  data() {
    return {
      info: null
    };
  },
  methods: {
    send() {
      axios.get('https://www.runoob.com/try/ajax/json_demo.json')
        .then(response => (this.info = response))
        .catch(function(error) {
          // 请求失败处理
          console.log(error);
        });
    }
  }
};
</script>

在这里插入图片描述

⚠️⚠️跨域访问问题,解决方案:vue.config.js 增加本地映射。

在这里插入图片描述

devServer: {
  proxy: {
    "/testapi":{    //testapi 这个用来和根路径 baseURL 进行匹配
      target: 'https://www.runoob.com', 
      changeOrigin: true,  
      pathRewrite: {
          '^/testapi': '/'
      }
    }
  }
}
  • 📍target:跨域请求的地址
  • 📍changeOrigin:是否允许跨域请求,在本地会创建一个虚拟服务端,发送接收请求数据,这样服务端和服务端进行数据的交互就不会有跨域问题
  • 📍pathRewrite:路径重写,替换请求地址,将地址 testapi 替换为空,示例:https://www.runoob.com/testapi/try/ajax/json_demo.json 转换成 https://www.runoob.com/try/ajax/json_demo.json

⚠️ 注意: ⚠️vue.config.js文件修改后,需要 npm run serve 重新启动,才能生效。

📌3、get请求url修改
在这里插入图片描述

<script>
import axios from "axios";

export default {
  data() {
    return {
      info: null
    };
  },
  methods: {
    send() {
      axios.get('/testapi/try/ajax/json_demo.json')
        .then(response => (this.info = response))
        .catch(function(error) {
          // 请求失败处理
          console.log(error);
        });
    }
  }
};
</script>

在这里插入图片描述

⚠️ 注: 可以通过 params 属性指定请求的 URL 参数对象,参数将拼接在 url 上。

2.3 API

axios 可以通过配置(config)来发送请求。config 指的是一个包含请求配置的对象。它可以包含各种属性,用于设置请求的细节和行为。

具体来说,config对象 可以包含以下属性:

  • url: 请求的 URL 地址。
  • method: 请求的 HTTP 方法,例如 GET、POST、PUT、DELETE 等。
  • params: 请求的 URL 参数,一个键值对形式的对象参数拼接在 url 上
  • data: 请求的数据,一个 JavaScript 对象或 FormData 对象参数放在请求体中
  • headers: 请求头对象,包含请求头信息的键值对。例如设置 token 等。
  • timeout: 请求的超时时间,单位是毫秒。
  • responseType: 响应的数据类型,例如 json、text、blob 等。
  • withCredentials: 是否携带跨域请求时的 Cookie 信息。
  • auth: 用于设置 HTTP 基本认证信息的对象,包含用户名和密码。
  • onUploadProgress: 上传进度回调函数。
  • onDownloadProgress: 下载进度回调函数。

以上仅列出了一些常用的配置属性,实际上 config 对象还可以包含其他属性,例如 validateStatus、maxRedirects、proxy 等等。

2.3.1 axios(config)

axios({
    method:"GET",
    url: '/testapi/try/ajax/json_demo.json',
    params: {
      firstParam: "111",
      secondParam: "222"
    }
  })
  .then(response => this.info = response)
  .catch(error => {
      // 请求失败处理
      console.log(error);
  });
}

最终请求地址:try/ajax/json_demo.json?firstParam=111&secondParam=222

⚠️ 注意: ⚠️默认的请求方式是 GET,如果不写 method,默认 method:"GET"

2.3.2 axios(url[,config])

axios('/testapi/try/ajax/json_demo.json', {
  method:"GET",
  params: {
    firstParam: "111",
    secondParam: "222"
  }
})
.then(response => (this.info = response))
.catch(function(error) {
    // 请求失败处理
    console.log(error);
});

🎈[,config]是可选项,如果没有请求参数,可以简写:

axios('/testapi/try/ajax/json_demo.json')
.then(response => (this.info = response))
.catch(function(error) {
    // 请求失败处理
    console.log(error);
});

2.3.3 请求方式的别名

axios.request(config);
axios.get(url[,config]);
axios.delete(url[,config]);
axios.head(url[,config]);
axios.post(url[,data[,config]]);
axios.put(url[,data[,config]])
axios.patch(url[,data[,config]])

📌示例:

axios.get('/testapi/try/ajax/json_demo.json')

☝️ 这里对所有已经支持的请求方式都提供了方便的别名,当我们在使用别名方法的时候,urlmethoddata这几个参数不需要在配置中声明。

2.3.4 axios.create([config])

📌1、创建一个axios实例,并且可以自定义其配置。

var instance = axios.create({
  baseURL:"https://some-domain.com/api/",
  timeout:1000,
  headers: {'X-Custom-Header':'foobar'}
});

可以统一配置 baseURL

📌2、用创建的实例对象发送请求

instance.get('/a.json',{
	timeout: 3000
}).then()

⚠️ 注: 使用创建的 axios 实例请求时,请求的配置项将与实例的配置合并。优先级axios请求配置 > axios实例配置 > axios全局配置

2.4 POST 方法

通过 data 属性指定请求数据对象,参数将放在 请求体 中。

//方式一:
axios('/testapi/try/ajax/demo_axios_post.php', {
    method: "POST"
  })
  .then(response => (this.info = response))
  .catch(function(error) {
      // 请求失败处理
      console.log(error);
  });
}

//方式二:
axios({
  method:"POST",
  url: '/testapi/try/ajax/demo_axios_post.php'
})

//方式三:
axios.post('/testapi/try/ajax/demo_axios_post.php')

💦 POST 方法传递参数格式如下:

//方式一:
axios({
  method:"POST",
  url: '/testapi/try/ajax/demo_axios_post.php',
  data: {
    firstName: 'Fred',        // 参数 firstName
    lastName: 'Flintstone'    // 参数 lastName
  }
})

//方式二:
axios.post('/testapi/try/ajax/demo_axios_post.php', {
  firstName: 'Fred',        // 参数 firstName
  lastName: 'Flintstone'    // 参数 lastName
})

最终请求地址:try/ajax/demo_axios_post.php  
报文体:{firstName: "Fred", lastName: "Flintstone"}

2.5 执行多个并发请求

axios 可以同时发送多个请求,然后等待所有请求返回后再进行下一步处理。

  • 📌axios.all(iterable):iterable 是一个可以迭代的参数,如数组等
  • 📌axios.spread(callback):callback 要等到所有请求都完成才会执行
<script>
import axios from "axios";

function getUserList() {
  return axios.get('/testapi/try/ajax/json_demo.json')
}

function getOrderList() {
  return axios.post('/testapi/try/ajax/demo_axios_post.php');
}

export default {
  data() {
    return {
      info: null
    };
  },
  methods: {
    send() {
      axios.all([getUserList(), getOrderList()])
      .then(axios.spread( (user, order) => {
          console.log(user.data)
          console.log(order.data)
          
          this.info = user.data
      }))
      .catch(function(error) {
          // 请求失败处理
          console.log(error);
      });
    }
  }
};
</script>

在这里插入图片描述

2.5.1 数组形式请求

<script>
import axios from "axios";

// 1、创建axios实例,设置请求超时时间
const instance = axios.create({
  timeout: 15000
})

// 2、创建请求数组
const requestArray = [
  instance.get('/testapi/try/ajax/json_demo.json'),
  instance.post('/testapi/try/ajax/demo_axios_post.php')
]

export default {
  data() {
    return {
      info: null
    };
  },
  methods: {
    send() {
      // 3、使用多个并发请求
      axios.all(requestArray)
      .then(axios.spread( (...result) => {
          console.log(result[0].data)
          console.log(result[1].data)
          
          this.info = result[0].data
      }))
      .catch(function(error) {
          // 请求失败处理
          console.log(error);
      });
    }
  }
};
</script>

在这里插入图片描述

⚠️ 注: axios.spread( (...result) => {} ) ,使用 展开运算符 遍历返回结果集。

3 配置

3.1 请求的配置(request config)

以下就是请求的配置选项,只有 url 选项是必须的,如果 method 选项未定义,那么它默认是以GET的方式发出请求

{
  // `url` 是用于请求的服务器 URL
  url: "/user",

  // `method` 是创建请求时使用的方法
  method: "get", // 默认是 get

  // `baseURL` 将自动加在 `url` 前面,除非 `url` 是一个绝对 URL。
  // 它可以通过设置一个 `baseURL` 便于为 axios 实例的方法传递相对 URL
  baseURL: "https://some-domain.com/api/",

  // `transformRequest` 允许在向服务器发送前,修改请求数据
  // 只能用在 "PUT", "POST" 和 "PATCH" 这几个请求方法
  // 后面数组中的函数必须返回一个字符串,或 ArrayBuffer,或 Stream
  transformRequest: [function (data) {
    // 对 data 进行任意转换处理

    return data;
  }],

  // `transformResponse` 在传递给 then/catch 前,允许修改响应数据
  transformResponse: [function (data) {
    // 对 data 进行任意转换处理

    return data;
  }],

  // `headers` 是即将被发送的自定义请求头
  headers: {"X-Requested-With": "XMLHttpRequest"},

  // `params` 是即将与请求一起发送的 URL 参数
  // 必须是一个无格式对象(plain object)或 URLSearchParams 对象
  params: {
    ID: 12345
  },

  // `paramsSerializer` 是一个负责 `params` 序列化的函数
  // (e.g. https://www.npmjs.com/package/qs, http://api.jquery.com/jquery.param/)
  paramsSerializer: function(params) {
    return Qs.stringify(params, {arrayFormat: "brackets"})
  },

  // `data` 是作为请求主体被发送的数据
  // 只适用于这些请求方法 "PUT", "POST", 和 "PATCH"
  // 在没有设置 `transformRequest` 时,必须是以下类型之一:
  // - string, plain object, ArrayBuffer, ArrayBufferView, URLSearchParams
  // - 浏览器专属:FormData, File, Blob
  // - Node 专属: Stream
  data: {
    firstName: "Fred"
  },

  // `timeout` 指定请求超时的毫秒数(0 表示无超时时间)
  // 如果请求花费了超过 `timeout` 的时间,请求将被中断
  timeout: 1000,

  // `withCredentials` 表示跨域请求时是否需要使用凭证
  withCredentials: false, // 默认的

  // `adapter` 允许自定义处理请求,以使测试更轻松
  // 返回一个 promise 并应用一个有效的响应 (查阅 [response docs](#response-api)).
  adapter: function (config) {
    /* ... */
  },

  // `auth` 表示应该使用 HTTP 基础验证,并提供凭据
  // 这将设置一个 `Authorization` 头,覆写掉现有的任意使用 `headers` 设置的自定义 `Authorization`头
  auth: {
    username: "janedoe",
    password: "s00pers3cret"
  },

  // `responseType` 表示服务器响应的数据类型,可以是 "arraybuffer", "blob", "document", "json", "text", "stream"
  responseType: "json", // 默认的

  // `xsrfCookieName` 是用作 xsrf token 的值的cookie的名称
  xsrfCookieName: "XSRF-TOKEN", // default

  // `xsrfHeaderName` 是承载 xsrf token 的值的 HTTP 头的名称
  xsrfHeaderName: "X-XSRF-TOKEN", // 默认的

  // `onUploadProgress` 允许为上传处理进度事件
  onUploadProgress: function (progressEvent) {
    // 对原生进度事件的处理
  },

  // `onDownloadProgress` 允许为下载处理进度事件
  onDownloadProgress: function (progressEvent) {
    // 对原生进度事件的处理
  },

  // `maxContentLength` 定义允许的响应内容的最大尺寸
  maxContentLength: 2000,

  // `validateStatus` 定义对于给定的HTTP 响应状态码是 resolve 或 reject  promise 。如果 `validateStatus` 返回 `true` (或者设置为 `null` 或 `undefined`),promise 将被 resolve; 否则,promise 将被 rejecte
  validateStatus: function (status) {
    return status &gt;= 200 &amp;&amp; status &lt; 300; // 默认的
  },

  // `maxRedirects` 定义在 node.js 中 follow 的最大重定向数目
  // 如果设置为0,将不会 follow 任何重定向
  maxRedirects: 5, // 默认的

  // `httpAgent` 和 `httpsAgent` 分别在 node.js 中用于定义在执行 http 和 https 时使用的自定义代理。允许像这样配置选项:
  // `keepAlive` 默认没有启用
  httpAgent: new http.Agent({ keepAlive: true }),
  httpsAgent: new https.Agent({ keepAlive: true }),

  // "proxy" 定义代理服务器的主机名称和端口
  // `auth` 表示 HTTP 基础验证应当用于连接代理,并提供凭据
  // 这将会设置一个 `Proxy-Authorization` 头,覆写掉已有的通过使用 `header` 设置的自定义 `Proxy-Authorization` 头。
  proxy: {
    host: "127.0.0.1",
    port: 9000,
    auth: : {
      username: "mikeymike",
      password: "rapunz3l"
    }
  },

  // `cancelToken` 指定用于取消请求的 cancel token
  // (查看后面的 Cancellation 这节了解更多)
  cancelToken: new CancelToken(function (cancel) {
  })
}

3.2 返回的内容

📅 axios请求的响应包含以下信息:

{
  // `data` 由服务器提供的响应
  data: {},

  // `status`  HTTP 状态码
  status: 200,

  // `statusText` 来自服务器响应的 HTTP 状态信息
  statusText: "OK",

  // `headers` 服务器响应的头
  headers: {},

  // `config` 是为请求提供的配置信息
  config: {}
}

📌 你可以这样来获取响应信息:

axios.get('/testapi/try/ajax/json_demo.json')
  .then(function(response) {
    console.log(response.data);
    console.log(response.status);
    console.log(response.statusText);
    console.log(response.headers);
    console.log(response.config);
  });

3.3 默认配置

3.3.1 全局默认配置

axios.defaults.baseURL = 'https://api.example.com';
axios.defaults.headers.common['Authorization'] = AUTH_TOKEN;
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';

3.3.2 自定义的实例默认设置

// 创建实例时设置配置的默认值
var instance = axios.create({
  baseURL: 'https://api.example.com'
});

// 在实例已创建后修改默认值
instance.defaults.headers.common['Authorization'] = AUTH_TOKEN;

🎈优先级:axios请求配置 > axios实例配置 > axios全局配置

// 使用由库提供的配置的默认值来创建实例
// 此时超时配置的默认值是 `0`
var instance = axios.create();

// 覆写库的超时默认值
// 现在,在超时前,所有请求都会等待 2.5 秒
instance.defaults.timeout = 2500;

// 为已知需要花费很长时间的请求覆写超时设置
instance.get('/longRequest', {
  timeout: 5000
});

☝️ 最终 timeout: 5000

4 拦截器

Axios 拦截器是 Axios 库提供的强大功能,允许你在 请求发送前响应返回后 对它们进行统一处理。

  • 请求拦截器:修改请求配置(如添加请求头、Token、加密数据等)。
  • 响应拦截器:统一处理响应数据(如解析数据、处理错误状态码等)。
  • 全局管理:统一处理加载状态、错误提示、日志记录等。

4.1 请求拦截器

// 请求拦截器
axios.interceptors.request.use(
  config => {
    // 在发送请求前修改配置
    config.headers.Authorization = 'Bearer token';
    return config; // 必须返回修改后的配置
  },
  error => {
    console.log("请求拦截器1调用失败");
    return Promise.reject(error)
  })

4.2 响应拦截器

// 响应拦截器
axios.interceptors.response.use(response => {
  // 对响应数据做处理
  if (response.status === 200) {
    console.log("响应拦截器1调用成功");
    if (response.data.code === 511) {
      // 未授权调取授权接口
    } else if (response.data.code === 510) {
      // 未登录跳转登录页
    } else {
      return Promise.resolve(response)
    }
  } else {
    return Promise.reject(response)
  }
}, error => {
  // 我们可以在这里对异常状态作统一处理
  if (error.response.status) {
    // 处理请求失败的情况
    // 对不同返回码对相应处理
    console.log("响应拦截器1调用失败");
    return Promise.reject(error.response)
  }
})

4.3 拦截器执行顺序

  • 请求拦截器:按添加顺序依次执行(先添加的先执行)。
  • 响应拦截器:按添加顺序的相反顺序执行(后添加的先执行)。
  • 若存在多个拦截器,执行顺序类似“洋葱模型”。

4.4 应用场景

4.4.1 Token 自动添加

axios.interceptors.request.use(config => {
  config.headers.Authorization = localStorage.getItem('token');
  return config;
});

4.4.2 全局加载状态管理

let loadingCount = 0;
axios.interceptors.request.use(config => {
  loadingCount++;
  showLoading();
  return config;
});

axios.interceptors.response.use(
  response => {
    if (--loadingCount === 0) hideLoading();
    return response;
  },
  error => {
    if (--loadingCount === 0) hideLoading();
    return Promise.reject(error);
  }
);

4.4.3 错误统一处理

axios.interceptors.response.use(
  response => response,
  error => {
    const { status } = error.response;
    if (status === 403) {
      router.push('/login');
    }
    return Promise.reject(error);
  }
);

4.5 注意事项

  • 异步操作:若拦截器中有异步逻辑(如 Token 刷新),需返回 Promise
  • 谨慎修改配置:避免直接修改原始 config 对象,建议创建新对象。
  • 拦截器与实例:可以为不同的 Axios 实例设置独立的拦截器。

完整示例:

// 创建 Axios 实例
const instance = axios.create({
  baseURL: 'https://api.example.com',
});

// 请求拦截器
instance.interceptors.request.use(
  (config) => {
    config.headers['X-Requested-With'] = 'XMLHttpRequest';
    return config;
  },
  (error) => Promise.reject(error)
);

// 响应拦截器
instance.interceptors.response.use(
  (response) => response.data,
  (error) => {
    if (error.response.status === 500) {
      console.error("服务器错误!");
    }
    return Promise.reject(error);
  }
);

// 使用实例发送请求
instance.get('/user').then(data => {
  console.log(data);
});

📚参考文章:
📖axios基本用法
📖Vue3 Ajax(axios) 菜鸟教程
https://blog.csdn.net/m0_60429030/article/details/127717453

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

不会叫的狼

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值