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>

在这里插入图片描述

2.3 API

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

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

  1. url: 请求的URL地址。
  2. method: 请求的HTTP方法,例如GET、POST、PUT、DELETE等。
  3. params: 请求的URL参数,一个键值对形式的对象。
  4. data: 请求的数据,一个JavaScript对象或FormData对象。
  5. headers: 请求头对象,包含请求头信息的键值对。
  6. timeout: 请求的超时时间,单位是毫秒。
  7. responseType: 响应的数据类型,例如json、text、blob等。
  8. withCredentials: 是否携带跨域请求时的Cookie信息。
  9. auth: 用于设置HTTP基本认证信息的对象,包含用户名和密码。
  10. onUploadProgress: 上传进度回调函数。
  11. 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(function(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'}
});

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

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

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

2.4 POST 方法

//方式一:
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很好用,其中之一就是它的拦截器十分强大,我们就可以为请求和响应设置拦截器,比如请求拦截器可以在每个请求里加上token,做了统一处理后维护起来也方便,响应拦截器可以在接收到响应后先做一层操作,如根据状态码判断登录状态、授权。

4.1 请求拦截器

// 请求拦截器
axios.interceptors.request.use(
  config => {
    // 每次发送请求之前,此处做校验
    console.log("请求拦截器1调用成功");
    return config
  },
  error => {
    console.log("请求拦截器1调用失败");
    return Promise.reject(error)
  })

4.2 响应拦截器

// 响应拦截器
axios.interceptors.response.use(response => {
  // 如果返回的状态码为200,说明接口请求成功,可以正常拿到数据
  // 否则的话抛出错误
  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)
  }
})
<script>
import axios from "axios";

axios.interceptors.request.use(...);
axios.interceptors.response.use(...);

export default {
  data() {
    return {
      info: ""
    };
  },
  methods: {
    send() {
       axios.get('/testapi/try/ajax/json_demo.json')
       .then( response => {
          console.log(response.status);
          console.log(response.data);
       })
    }
  }
};
</script>

在这里插入图片描述

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

  • 8
    点赞
  • 35
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
Vue3中配置axios需要以下几个步骤: 1. 首先,在项目根目录下通过npm安装axiosvue-axios依赖,可以使用以下命令进行安装:`npm install --save axios vue-axios` 2. 在src根目录下创建一个service文件夹,并在该文件夹内创建一个axios.js文件。 3. 在axios.js文件中引入axios库和服务文件:`import axios from "axios";` 4. 创建一个axios实例并进行相关配置,例如设置超时时间:`const initAxios = axios.create({ timeout: 1800000 })` 5. 在axios.js文件中添加请求拦截器和响应拦截器。请求拦截器可以在发送请求前做一些操作,例如添加请求头信息。响应拦截器可以处理返回的数据,例如判断响应结果是否成功:`initAxios.interceptors.request.use(...)`,`initAxios.interceptors.response.use(...)` 6. 最后,导出这个axios实例供其他地方使用:`export default () => initAxios` 在Vue3中使用axios的步骤如下: 1. 在需要使用axios的组件或文件中引入axios服务:`import _service from "@/service";` 2. 使用axios发送请求,可以调用之前定义的接口方法,例如调用getList接口:`_service.getList({你的参数}).then(res => { console.log(res) })` 请注意,Vue3中没有this关键字,所以可以直接引用axios服务。如果项目较大,接口较多,可以将接口分模块定义,并在使用时分模块导入。例如,在admin模块中定义接口。 以上就是在Vue3中配置axios和使用axios的方法。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *2* *3* [Vue3使用axios的配置教程详解](https://blog.csdn.net/qq_38682174/article/details/125416084)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 100%"] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

不会叫的狼

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

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

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

打赏作者

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

抵扣说明:

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

余额充值