前端热门技术axios详细讲解(一)——基本使用方法
前言: axios 作为前端必学技术,它实质上是一个基于XMLHttpRequest和 promise 的 HTTP 库,Vue和React都推荐使用它发送ajax请求。 本文主要讲述axios发送请求时要掌握的知识点。
一、axios的特点
-
在浏览器和node中都可以使用 支持 Promise API 可以拦截请求、响应 转换请求数据、响应数据 取消请求 自动转换 JSON 数据 客户端支持防御 XSRF
传送门:
二、使用方法
在项目中安装:
$ npm install axios
或
$ yarn add axios
使用cdn:
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
1. 默认配置
我们可以给axios设置一个默认的基本配置,里面包括 url、method 等,设置好之后就不用每次添加了。(只有 url 是必需的,如果没有指定 method,请求将默认使用 get 方法。)
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;
2. 自定义全局配置
// 设置配置对象 const configOptions={ baseURL: https://api.example.com, timeout:30000, // 超时取消请求 withCredentials: true, // 表示跨域请求时是否需要使用凭证,默认false } //创建实例时,传入配置 const instance = axios.create(configOptions); // 实例创建后更改默认值 axios.defaults.headers.post[Content-Type] = application/x-www-form-urlencoded;
注意:配置是有优先级的,这个顺序是:在 lib/defaults.js 找到的库的默认值 < 是实例的 defaults 属性 < 请求的 config 参数。后者将优先于前者。
3. 请求配置
{ // `url` 是用于请求的服务器 URL url: /user, // `method` 是创建请求时使用的方法 method: get, // default // `baseURL` 将自动加在 `url` 前面,除非 `url` 是一个绝对 URL。 // 它可以通过设置一个 `baseURL` 便于为 axios 实例的方法传递相对 URL baseURL: https://some-domain.com/api/, /* `transformRequest`:向服务器发送前,修改请求数据; 只能用在 PUT, POST 和 PATCH 这几个请求方法; 后面数组中的函数必须返回一个字符串,或 ArrayBuffer,或 Stream */ transformRequest: [function (data, headers) { // 对 data 进行任意转换处理 return data; }], // `transformResponse` 在传递给 then/catch 前,修改响应数据 transformResponse: [function (data) { // 对 data 进行任意转换处理 return data; }], }
官方为了方便起见,给axios的常用方法专门起了别名,可以直接像这样使用:axios.get(),axios.post(),axois.put()等等。如图:
这里只介绍基本的,更多详细内容请。
4. 发送get请求
get 请求传参可以直接加在地址后,或写在params对象中。
const axios = require(axios).default; // 第一种:直接加在地址后,用问号?传参 axios.get(/user?ID=12345) .then(function (response) { console.log(response); }) .catch(function (error) { console.log(error); }) .then(function () { // always executed }); // 第二种:在花括号中用params对象传参 axios.get(/user, { params: { ID: 12345 } }) // Want to use async/await? Add the `async` keyword to your outer function/method. async function getUser() { try { const response = await axios.get(/user?ID=12345); console.log(response); } catch (error) { console.error(error); } }
5. 发送post请求
axios.post(/user, { firstName: Fred, lastName: Flintstone }) .then(function (response) { console.log(response); }) .catch(function (error) { console.log(error); });
下一篇:
测试经理管理测试团队的测试质量