当前位置:   article > 正文

axios快速入门

axios

一、环境配置

1.1概述

上古浏览器页面在向服务器请求数据时,因为返回的是整个页面的数据,页面都会强制刷新一下,这对于用户来讲并不是很友好。并且我们只是需要修改页面的部分数据,但是从服务器端发送的却是整个页面的数据,十分消耗网络资源。而我们只是需要修改页面的部分数据,也希望不刷新页面,因此异步网络请求就应运而生。

Ajax(Asynchronous JavaScript and XML):异步网络请求。Ajax能够让页面无刷新的请求数据。

实现ajax的方式有多种,如jQuery封装的ajax,原生的XMLHttpRequest,以及axios。但各种方式都有利弊

原生的XMLHttpRequest的配置和调用方式都很繁琐,实现异步请求十分麻烦
jQuery的ajax相对于原生的ajax是非常好用的,但是没有必要因为要用ajax异步网络请求而引用jQuery框架

1.2安装

pnpm i axios --save-dev

在项目中创建untils/request.js文件

  1. import axios from 'axios'
  2. // 创建可一个新的axios对象
  3. const request = axios.create({
  4. baseURL: 'http://localhost:9090', // 后端的接口地址 ip:port
  5. timeout: 30000
  6. })
  7. // request 拦截器
  8. // 可以自请求发送前对请求做一些处理
  9. // 比如统一加token,对请求参数统一加密
  10. request.interceptors.request.use(config => {
  11. config.headers['Content-Type'] = 'application/json;charset=utf-8';
  12. // let user = localStorage.getItem("user") ? JSON.parse(localStorage.getItem("user")) : null
  13. // config.headers['token'] = 'token' // 设置请求头
  14. return config
  15. }, error => {
  16. console.error('request error: ' + error) // for debug
  17. return Promise.reject(error)
  18. });
  19. // response 拦截器
  20. // 可以在接口响应后统一处理结果
  21. request.interceptors.response.use(
  22. response => {
  23. let res = response.data;
  24. // 兼容服务端返回的字符串数据
  25. if (typeof res === 'string') {
  26. res = res ? JSON.parse(res) : res
  27. }
  28. return res;
  29. },
  30. error => {
  31. console.error('response error: ' + error) // for debug
  32. return Promise.reject(error)
  33. }
  34. )
  35. export default request

1.3示例

  1. import axios from "axios";
  2. data() {
  3. return {
  4. users: []
  5. }
  6. }
  7. mounted() { // 页面加载完成之后触发
  8. axios.get('http://localhost:9090/user/selectAll').then(res => {
  9. console.log(res.data) // 后台返回的数据
  10. // res.data = { // 数据格式
  11. // code: '200',
  12. // msg: '请求成功',
  13. // data: {
  14. //
  15. // }
  16. // }
  17. })
  18. },

@CrossOrigin

1.4相关文档

请求配置 | Axios中文文档 | Axios中文网

二、跨域资源访问

2.1会话存储

随着富客户端快速发展,普通本地存储(cookie)无法满足前端需要的大量数据的存储需求 HTML5,引入Web存储,Web应用程序可以在用户的浏览器中本地存储数据

  • 包括本地数据库技术 IndexedDB/WebSQL等
  • 包括基于键值对 LocalStorage/SessionStorage

Web Storage提供了两种在客户端存储数据的方式,即**LocalStorage和SessionStorage**,它们都用于以键值对的形式保存数据。具体如下:

  • LocalStorage,本地全局数据存储。永久性数据,需手动删除,无加密,可跨域调用
  • SessionStorage,当前页面标签存储。仅与当前页面绑定,标签/浏览器关闭,数据自动销毁

2.2CORS policy

发出请求的地址与目标地址,域名(IP)+端口一致,即为,同源 浏览器持有用户大量敏感数据。因此,同源安全策略,即限制跨域请求(尤其基于Ajax发出的请求),是浏览器的一种安全机制

方法1,后端允许跨域请求

方法1,前端同时需要修改axios全局请求的基本地址。无需vue配置 方法1,不利于开发环境与生产环境间的切换

方法2,后端无需改动。前端, vue.config.js添加配置

此方法仅在开发测试环境下有效

三、 Axios基本入门

3.1概述

axios可以请求的方法:

  • get:获取数据,请求指定的信息,返回实体对象
  • post:向指定资源提交数据(例如表单提交或文件上传)
  • put:更新数据,从客户端向服务器传送的数据取代指定的文档的内容
  • patch:更新数据,是对put方法的补充,用来对已知资源进行局部更新
  • delete:请求服务器删除指定的数据

3.2get方法

方式一:请求别名的使用

axios.get(url[, config]) 用于获取数据  

  • 如果不带有参数,代码如下:
  1. <script setup>
  2. import { onMounted } from 'vue';
  3. import axios from 'axios';
  4. const fetchData = async () => {
  5. try {
  6. const response = await axios.get('/data.json');
  7. console.log('数据:', response);
  8. console.log('真正的数据:', response.data);
  9. } catch (error) {
  10. console.error(error);
  11. }
  12. };
  13. onMounted(() => {
  14. fetchData();
  15. });
  16. </script>
  • 如果带有参数,代码如下:
  1. <script setup>
  2. import axios from 'axios';
  3. // 第一种方式:将参数直接写在 URL 中
  4. async function fetchUserByIdInUrl() {
  5. try {
  6. const response = await axios.get("/data.json?id=5");
  7. console.log("数据(URL 直接携带参数):", response.data);
  8. } catch (error) {
  9. console.error("错误(URL 直接携带参数):", error);
  10. }
  11. }
  12. // 第二种方式:将参数写在 params 对象中
  13. async function fetchUserByIdInParams() {
  14. try {
  15. const response = await axios.get("/data.json", {
  16. params: {
  17. id: 5,
  18. },
  19. });
  20. console.log("数据(params 对象传递参数):", response.data);
  21. } catch (error) {
  22. console.error("错误(params 对象传递参数):", error);
  23. }
  24. }
  25. // 使用 async/await
  26. async function fetchUserWithAsyncAwait() {
  27. try {
  28. const response = await axios.get("/user?ID=12345");
  29. console.log("数据(async/await):", response.data);
  30. } catch (error) {
  31. console.error("错误(async/await):", error);
  32. }
  33. }
  34. // 在组件挂载后执行请求
  35. onMounted(() => {
  36. fetchUserByIdInUrl();
  37. fetchUserByIdInParams();
  38. fetchUserWithAsyncAwait();
  39. });
  40. </script>

此时表示,参数为id=5,最终的请求路径Request URL:http://localhost:8080/data.json?id=5

方式二: 通过向axios传递相关配置来创建请求

  • 如果不带参数,代码如下:
  1. <script setup>
  2. import axios from 'axios';
  3. async function fetchData() {
  4. try {
  5. const response = await axios({
  6. method: "get",
  7. url: "/data.json"
  8. });
  9. console.log("数据:", response.data);
  10. } catch (error) {
  11. console.error("错误:", error);
  12. }
  13. }
  14. onMounted(() => {
  15. fetchData();
  16. });
  17. </script>

如果带有参数,代码如下

  1. <script setup>
  2. import axios from 'axios';
  3. async function fetchData() {
  4. try {
  5. const response = await axios({
  6. method: "get",
  7. url: "/data.json",
  8. params: {
  9. id: 5,
  10. },
  11. });
  12. console.log("数据:", response.data);
  13. } catch (error) {
  14. console.error("错误:", error);
  15. }
  16. }
  17. onMounted(() => {
  18. fetchData();
  19. });
  20. </script>

此时表示,参数为id=5,最终的请求路径Request URL:http://localhost:8080/data.json?id=5

总结

get请求时,参数会以url string 的形式进行传递,即?后的字符串则为其请求参数,并以&做为分隔符。 

 

3.3post方法

post请求常用的数据请求格式有三种: 

  1. Content-Type : application/x-www-form-urlencoded。ajax默认的数据格式。请求体中的数据会以json字符串的形式发送到后端。
  2. Content-Type : application/json ; charset=utf-8。axios默认的数据格式。请求体中的数据会以普通表单形式(键值对)发送到后端。
  3. Content-Type : multipart/form-data 。它会将请求体的数据处理为一条消息,以标签为单元,用分隔符分开。既可以上传键值对,也可以上传文件。

 Content-Type:application/x-www-form-urlencoded

  1. <script setup>
  2. import axios from 'axios';
  3. import qs from 'qs';
  4. async function sendData() {
  5. const data = { uname: "dingding", upwd: "123456" };
  6. try {
  7. const response = await axios.post("/date.json", qs.stringify({ data }));
  8. console.log("响应:", response);
  9. } catch (error) {
  10. console.error("错误:", error);
  11. }
  12. }
  13. onMounted(() => {
  14. sendData();
  15. });
  16. </script>

  Content-Type: multipart/form-data(常用于表单提交(图片上传、文件上传))

  1. <script setup>
  2. import axios from 'axios';
  3. // 定义一个异步函数,用于发送数据
  4. async function sendData() {
  5. // 创建所需发送的数据对象
  6. const data = { uname: "dingding", upwd: 123456 };
  7. // 创建一个 FormData 对象用于存储要发送的数据
  8. const formData = new FormData();
  9. // 遍历数据对象的属性,将它们添加到 FormData 对象中
  10. for (const key in data) {
  11. formData.append(key, data[key]);
  12. }
  13. // 打印 FormData 对象,便于调试
  14. console.log(formData);
  15. try {
  16. // 使用 Axios 发起 POST 请求,将 FormData 对象作为请求体
  17. const response = await axios.post("/date.json", formData);
  18. // 打印请求的响应数据
  19. console.log("响应数据:", response.data);
  20. } catch (error) {
  21. // 处理可能出现的错误
  22. console.error("请求错误:", error);
  23. }
  24. }
  25. // 在组件挂载后调用 sendData 函数,确保数据被发送
  26. onMounted(() => {
  27. sendData();
  28. });
  29. </script>

注意:form-data类型的相关请求信息

- 请求地址Request URL: http://localhost:8080/data.json

- 请求头中Content-Type: multipart/form-data; boundary=----WebKitFormBoundarySmuEKOlBaxhc0In2

- 参数形式:{uname: "dingding", upwd: 123456}

  Content-Type: application/json(常用)

  • 方式一:请求别名的使用

axios.post(url[, data[, config]]) 用于发送数据 `data`对象是作为请求主体被发送的数据  

axios发送post无参请求,代码如下:

  1. <script setup>
  2. import axios from 'axios';
  3. // 定义一个异步函数,用于发送 POST 请求
  4. async function sendPostRequest() {
  5. try {
  6. // 使用 Axios 发起 POST 请求,没有请求体
  7. const response = await axios.post("/data.json");
  8. // 打印请求的响应结果
  9. console.log("响应:", response);
  10. } catch (error) {
  11. // 处理可能出现的错误
  12. console.error("请求错误:", error);
  13. }
  14. }
  15. // 在组件挂载后调用 sendPostRequest 函数,确保请求被发送
  16. onMounted(() => {
  17. sendPostRequest();
  18. });
  19. </script>

axios发送post有参请求,2种传参形式,代码如下:

① 查询字符串形式

  1. <script setup>
  2. import axios from 'axios';
  3. // 定义一个异步函数,用于发送 POST 请求并携带参数
  4. async function sendPostRequestWithParams() {
  5. try {
  6. // 使用 Axios 发起 POST 请求,请求路径为 "/data.json",请求体为查询字符串 "uname=dingding&upwd=123456"
  7. const response = await axios.post("/data.json", "uname=dingding&upwd=123456");
  8. // 打印请求的响应结果
  9. console.log("响应:", response);
  10. } catch (error) {
  11. // 处理可能出现的错误
  12. console.error("请求错误:", error);
  13. }
  14. }
  15. // 在组件挂载后调用 sendPostRequestWithParams 函数,确保请求被发送
  16. onMounted(() => {
  17. sendPostRequestWithParams();
  18. });
  19. </script>

② 对象形式

  1. <script setup>
  2. import axios from 'axios';
  3. // 定义一个异步函数,用于发送 POST 请求并携带参数
  4. async function sendPostRequestWithJsonParams() {
  5. try {
  6. // 使用 Axios 发起 POST 请求,请求路径为 "/data.json",请求体为 JSON 对象 {uname: "dingding", upwd: 123456}
  7. const response = await axios.post("/data.json", { uname: "dingding", upwd: 123456 });
  8. // 打印请求的响应结果
  9. console.log("响应:", response);
  10. } catch (error) {
  11. // 处理可能出现的错误
  12. console.error("请求错误:", error);
  13. }
  14. }
  15. // 在组件挂载后调用 sendPostRequestWithJsonParams 函数,确保请求被发送
  16. onMounted(() => {
  17. sendPostRequestWithJsonParams();
  18. });
  19. </script>
  • 方式二:通过向axios传递相关配置来创建请求
  1. <script setup>
  2. import axios from 'axios';
  3. // 定义一个异步函数,用于发送 POST 请求并携带参数
  4. async function sendPostRequestWithParams() {
  5. const data = { uname: "dingding", upwd: 123456 };
  6. try {
  7. // 使用 Axios 发起 POST 请求,请求路径为 "/data.json",请求体为 JSON 对象 {uname: "dingding", upwd: 123456}
  8. const response = await axios.post("/data.json", data);
  9. // 打印请求的响应结果
  10. console.log("响应:", response);
  11. } catch (error) {
  12. // 处理可能出现的错误
  13. console.error("请求错误:", error);
  14. }
  15. }
  16. // 在组件挂载后调用 sendPostRequestWithParams 函数,确保请求被发送
  17. onMounted(() => {
  18. sendPostRequestWithParams();
  19. });
  20. </script>

3.4put和patch方法 

put和patch请求与post请求用法一样类似,同样有x-www-form-urlencoded、applicition/json和form-data,只有method不同,其他相同。在此不过多赘述了,简单写一下!  

  1. <script setup>
  2. import axios from 'axios';
  3. // 定义一个异步函数,用于发送 PUT 请求并携带参数
  4. async function sendPutRequestWithParams() {
  5. const data = { uname: "dingding", upwd: 123456 };
  6. try {
  7. // 使用 Axios 发起 PUT 请求,请求路径为 "/data.json",请求体为 JSON 对象 {uname: "dingding", upwd: 123456}
  8. const putResponse = await axios.put("/data.json", data);
  9. // 打印 PUT 请求的响应结果
  10. console.log("PUT 响应:", putResponse);
  11. } catch (error) {
  12. // 处理可能出现的错误
  13. console.error("PUT 请求错误:", error);
  14. }
  15. }
  16. // 定义一个异步函数,用于发送 PATCH 请求并携带参数
  17. async function sendPatchRequestWithParams() {
  18. const data = { uname: "dingding", upwd: 123456 };
  19. try {
  20. // 使用 Axios 发起 PATCH 请求,请求路径为 "/data.json",请求体为 JSON 对象 {uname: "dingding", upwd: 123456}
  21. const patchResponse = await axios.patch("/data.json", data);
  22. // 打印 PATCH 请求的响应结果
  23. console.log("PATCH 响应:", patchResponse);
  24. } catch (error) {
  25. // 处理可能出现的错误
  26. console.error("PATCH 请求错误:", error);
  27. }
  28. }
  29. // 在组件挂载后分别调用 sendPutRequestWithParams 和 sendPatchRequestWithParams 函数,确保请求被发送
  30. onMounted(() => {
  31. sendPutRequestWithParams();
  32. sendPatchRequestWithParams();
  33. });
  34. </script>

 3.5delete方法

axios.delete(url[, config])与axios.get(url[, config])用法基本相似,但是作用不同,它用于删除数据,同get方法一样也可以有几种写法 。

delete请求有时候需要把参数拼接到URL上,有时候像post请求那样把参数放在请求体里面。至于具体怎么调用,需要和后端商量好!

  • 方式一:get - params
  1. <script setup>
  2. import axios from 'axios';
  3. // 使用别名法:DELETE 请求携带 params 参数
  4. async function sendDeleteRequestWithParams() {
  5. try {
  6. // 1. 通过 params 对象传递参数
  7. await axios.delete("/data.json", {
  8. params: {
  9. id: 12,
  10. },
  11. }).then((res) => {
  12. console.log(res, "delete (params object)");
  13. });
  14. // 2. 通过查询字符串形式传递参数
  15. await axios.delete("/data.json?id=2", {
  16. params: {
  17. id: 12,
  18. },
  19. }).then((res) => {
  20. console.log(res, "delete (query string)");
  21. });
  22. } catch (error) {
  23. console.error("DELETE 请求错误:", error);
  24. }
  25. }
  26. // 不使用别名法:通过传递相关配置创建 DELETE 请求
  27. async function sendDeleteRequestWithConfig() {
  28. const params = {
  29. id: 5,
  30. };
  31. try {
  32. const response = await axios({
  33. method: "delete",
  34. url: "/data.json",
  35. params: params,
  36. });
  37. console.log(response);
  38. } catch (error) {
  39. console.error("DELETE 请求错误:", error);
  40. }
  41. }
  42. // 在组件挂载后分别调用 sendDeleteRequestWithParams 和 sendDeleteRequestWithConfig 函数,确保请求被发送
  43. onMounted(() => {
  44. sendDeleteRequestWithParams();
  45. sendDeleteRequestWithConfig();
  46. });
  47. </script>
  • 方式二:post - data

使用类似post请求方式,把axios.delete()中的params改为data,这样请求会把内容放入请求体里面

  1. <script setup>
  2. import axios from 'axios';
  3. // 使用别名法:DELETE 请求携带 data 参数(非标准用法)
  4. async function sendDeleteRequestWithDataAlias() {
  5. try {
  6. const response = await axios.delete("/data.json", {
  7. data: {
  8. id: 5,
  9. },
  10. });
  11. console.log(response, "DELETE with data (using alias)");
  12. } catch (error) {
  13. console.error("DELETE 请求错误(使用别名法):", error);
  14. }
  15. }
  16. // 不使用别名法:通过传递相关配置创建 DELETE 请求并携带 data 参数(非标准用法)
  17. async function sendDeleteRequestWithDataConfig() {
  18. const data = {
  19. id: 5,
  20. };
  21. try {
  22. const response = await axios({
  23. method: "delete",
  24. url: "/data.json",
  25. data: data,
  26. });
  27. console.log(response, "DELETE with data (using config)");
  28. } catch (error) {
  29. console.error("DELETE 请求错误(使用配置法):", error);
  30. }
  31. }
  32. // 在组件挂载后分别调用 sendDeleteRequestWithDataAlias 和 sendDeleteRequestWithDataConfig 函数,确保请求被发送
  33. onMounted(() => {
  34. sendDeleteRequestWithDataAlias();
  35. sendDeleteRequestWithDataConfig();
  36. });
  37. </script>

3.6并发请求 

`并发请求`: 在同一时间发送多个不同的请求到后端服务,最后同一处理不同服务的响应结果

  1. <script setup>
  2. import axios from 'axios';
  3. // 定义一个异步函数,用于并发请求并处理响应结果
  4. async function handleConcurrentRequests() {
  5. try {
  6. // 同时发起两个 GET 请求
  7. const [dataRes, cityRes] = await Promise.all([
  8. axios.get("/data.json"),
  9. axios.get("/city.json"),
  10. ]);
  11. // 打印两个请求的响应结果
  12. console.log("Data Response:", dataRes);
  13. console.log("City Response:", cityRes);
  14. } catch (error) {
  15. // 处理可能出现的错误
  16. console.error("并发请求错误:", error);
  17. }
  18. }
  19. // 在组件挂载后调用 handleConcurrentRequests 函数,确保请求被发送
  20. onMounted(() => {
  21. handleConcurrentRequests();
  22. });
  23. </script>

注意:axios.all的参数是请求函数的数组,在对应的回调then中,调用axios.spead对返回值进行处理即可。

并发请求的应用场景:需要同时进行多个请求,并且需要同时处理接口调用的返回值的时候,我们可以使用并发请求。

3.7Restful风格的API

  •   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]])
  1. <script setup>
  2. import axios from 'axios';
  3. const commonConfig = {
  4. baseURL: 'https://api.example.com/v1',
  5. headers: {
  6. 'Content-Type': 'application/json',
  7. Authorization: 'Bearer your-access-token',
  8. },
  9. };
  10. // 示例:使用 axios.request(config)
  11. async function makeRequestUsingRequest() {
  12. const customConfig = {
  13. ...commonConfig,
  14. method: 'GET',
  15. url: '/users/123',
  16. };
  17. try {
  18. const response = await axios.request(customConfig);
  19. console.log('axios.request:', response.data);
  20. } catch (error) {
  21. console.error('axios.request Error:', error.message);
  22. }
  23. }
  24. // 示例:使用 axios.get(url[, config])
  25. async function makeGetRequestUsingGetMethod() {
  26. const getEndpoint = '/users/123';
  27. const getConfig = {
  28. ...commonConfig,
  29. };
  30. try {
  31. const response = await axios.get(getEndpoint, getConfig);
  32. console.log('axios.get:', response.data);
  33. } catch (error) {
  34. console.error('axios.get Error:', error.message);
  35. }
  36. }
  37. // 示例:使用 axios.head(url[, config])
  38. async function makeHeadRequest() {
  39. const headEndpoint = '/users/123';
  40. const headConfig = {
  41. ...commonConfig,
  42. };
  43. try {
  44. const response = await axios.head(headEndpoint, headConfig);
  45. console.log('axios.head:', response.headers); // 注意:HEAD 请求的响应没有 data 属性,仅关注 headers
  46. } catch (error) {
  47. console.error('axios.head Error:', error.message);
  48. }
  49. }
  50. // 在组件挂载后调用各示例函数,确保请求被发送
  51. onMounted(() => {
  52. makeRequestUsingRequest();
  53. makeHeadRequest();
  54. });
  55. </script>

3.8响应信息

  1. {
  2. //data是服务器提供的响应
  3. data:{},
  4. //服务器返回的http状态码
  5. status: 200,
  6. //statusText是服务器返回的http状态信息
  7. statusText: 'ok',
  8. //heades是服务器响应中携带的headers
  9. headers:{},
  10. //config是axios进行的设置,目的是为了请求(request)
  11. config:{},
  12. }
  13. //使用then后,response中将包含上述信息
  14. axios.get('/user/12345').then(response={
  15. console.log(response.data);
  16. console.log(response.status);
  17. console.log(response.statusText);
  18. console.log(response.headers);
  19. console.log(response.config);
  20. })

四、Axios进阶用法

4.1axios实例的创建与配置

 axios实例的创建

比如:后端接口地址有多个(www.test.com、www.example.com),并且超时时长不同,比如1000ms、2000ms,这个时候,我们可以创建实例,利用axios实例进行网络请求。

思路如下:创建多个实例,配置不同的超时时长,用不同的实例去请求不同的接口。使用axios.acreate来创建实例,配置相关信息,进行网络请求。代码如下:

  1. <script setup>
  2. import axios from 'axios';
  3. // 创建 Axios 实例 1
  4. const instance1 = axios.create({
  5. baseURL: "http://localhost:8080",
  6. timeout: 1000,
  7. });
  8. // 使用实例 1 发送 GET 请求
  9. async function makeRequestUsingInstance1() {
  10. try {
  11. const response = await instance1.get("/data.json");
  12. console.log("Instance 1 Response:", response.data);
  13. } catch (error) {
  14. console.error("Instance 1 Error:", error.message);
  15. }
  16. }
  17. // 创建 Axios 实例 2
  18. const instance2 = axios.create({
  19. baseURL: "http://localhost:8081",
  20. timeout: 2000,
  21. });
  22. // 使用实例 2 发送 GET 请求
  23. async function makeRequestUsingInstance2() {
  24. try {
  25. const response = await instance2.get("/city.json");
  26. console.log("Instance 2 Response:", response.data);
  27. } catch (error) {
  28. console.error("Instance 2 Error:", error.message);
  29. }
  30. }
  31. // 在组件挂载后调用各示例函数,确保请求被发送
  32. onMounted(() => {
  33. makeRequestUsingInstance1();
  34. makeRequestUsingInstance2();
  35. });
  36. </script>

备注:此时我们就可以访问http://loacalhost:8080与http://loacalhost:8081两个不同域名的接口,并且使用不同的配置。

 axios实例的相关配置

(1)配置列表:

- baseURL:请求的域名 / 基本地址。

- timeout:请求的超时时长,默认:1000毫秒(ms),超过这个时长后端会报(返回)401超时。

- url:请求的路径。

- method:请求的方法。如:get、post、put、patch、delete等。

- headers:请求头。

- params:将请求参数拼接到url上

- data:将请求参数放置到请求体里

  1. let instance = axios.create({
  2. // 创建实例时设置配置默
  3. baseURL: "", //请求的域名/基本地址
  4. timeout: 2000, //请求的超时时长,单位毫秒,默认。
  5. url: "/data.json", //请求路径
  6. method: "get", //请求方法
  7. headers: {
  8. //设置请求头————我们可以给请求头添加一些参数
  9. token: "",
  10. post: {
  11. 'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'
  12. }
  13. },
  14. params: { id: 5 }, //将请求参数拼接到url上
  15. data: { id: 5 }, //将请求参数放置到请求体里
  16. });

(2)三种配置方式:

  • axios全局配置
  1. axios.defaults.baseURL = 'http://localhost:8080'
  2. axios.defaults.timeout = 2000

备注:在一个项目当中,我们经常存在需要多次请求同一个基本URL下的不同路由,如果每次发送请求都书写一遍基本URL无疑会产生大量的代码重复,因此,可以使用全局配置来简化代码。  默认配置 | Axios 中文文档 | Axios 中文网

  • axios实例配置
  1. let instance = axios.create();
  2. instance.defaults.timeout = 3000
  • axios请求配置
  1. instance.get('/data.json',{
  2. timeout:5000
  3. })

配置方式的优先级:axios全局配置 < axios实例配置 < axios请求配置

(3)常用参数配置的使用方法

  • 示例1:
  1. let instance1 = axios.create({
  2. baseURL: "http://localhost:9090",
  3. timeout: 1000,
  4. });
  5. instance1
  6. .get("/contactList", {
  7. params: {
  8. id: 5,
  9. },
  10. })
  11. .then((res) => {
  12. console.log(res);
  13. });

分析:配置的参数为baseURL:‘http://localhost:8080’,timeout:1000,method:‘get’,params:{ id:10},url:’/contactList’

  • 示例2:
  1. let instance2 = axios.create({
  2. baseURL: "http://localhost:8081",
  3. timeout: 3000,
  4. });
  5. instance2
  6. .get("/contactList", {
  7. timeout: 5000,
  8. })
  9. .then((res) => {
  10. console.log(res);
  11. });

分析:配置的参数为baseURL:‘http://localhost:8081’,timeout:5000,method:‘get’,url:’/contactList’

注意:最终的有效配置是由优先级高的覆盖优先级低的。

4.2拦截器

何为拦截器?就是在请求前或响应被处理前拦截他们,分为两种:请求拦截器响应拦截器

(1)axios拦截器的使用方法

  • 请求拦截器 ——在请求之前拦截请求
  1. // 添加请求拦截器
  2. /*需要拦截请求的原因
  3. * 1.config中包含了某些不符合服务器要求的信息
  4. * 2.发送网络请求的时候需要向用户展示一些加载中的图标
  5. * 3.网站需要登录才能请求资源,也就是需要token才能请求资源*/
  6. axios.interceptors.request.use(config => {
  7. // 在发送请求之前做些什么
  8. console.log(config)
  9. return config; //拦截器里一定要记得将拦截的结果处理后返回,否则无法进行数据获取
  10. }, err=>{
  11. // 对请求错误做些什么
  12. console.log(err)
  13. return Promise.reject(err) // 在请求错误的时候的逻辑处理
  14. });

  备注:可以为自定义 axios 实例添加拦截器 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/知新_RL/article/detail/783997
推荐阅读
相关标签