初学axios-AJAX

初学axios

1、概述

1.1 定义

Axios 是一个基于 promise 的网络请求库,可以作用于node.js 和浏览器中。

它是 isomorphic 的(即同一套代码可以运行在浏览器和node.js中)。
也就是说在服务端它使用原生 node.js的http 模块, 而在客户端 (浏览端) 则使用 XMLHttpRequestsaxios的返回结果是一个promise对象

1.2 axios的特性

  • 在浏览器创建 XMLHttpRequests
  • 在服务器node.js创建 http 请求
  • 支持 Promise API
  • 拦截请求和响应
  • 转换请求和响应数据
  • 取消请求
  • 自动转换JSON数据
  • 客户端支持防御XSRF

2、环境配置

Node.js,浏览器环境

2.1 axios安装引入

安装
npm install axios
引入
  • 方式一:html文件中引入下载好的axios.js文件
<script src="axios.min.js></script>
  • 方式二:引入cdn
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
  • 方式三:
    (1)commonJS方式:const axios = require('axios');
    (2)ES6方式:import axios from 'axios'

3、AxiosAPI基本使用

基本使用

3.2.1 axios(config)

通过设置一些配置属性来实现发送请求

  • 格式
axios({
	method:'', // 请求方式
	url:'', // url
	param:'', // 按照查询字符串形式拼接到url后的参数
	data:'', // 放在请求体中的参数
	...
}).then().catch()

例如:发送get请求和post请求

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <script src="https://cdn.bootcdn.net/ajax/libs/axios/1.2.0/axios.js"></script>
    <title>Document</title>
  </head>
  <body>
    <button onClick="sendGET()">发送get请求</button>
    <button onClick="sendPOST()">发送post请求</button>
    <script>
      function sendGET() {
        axios({
          url: "http://localhost:8080/user",
          method: "get",
        })
          .then((res) => {
            console.log(res.data);
          })
          .catch((err) => {
            console.log(err);
          });
      }

      function sendPOST() {
        axios({
          url: "http://localhost:8080/book",
          method: "post",
        })
          .then((res) => {
            console.log(res.data);
          })
          .catch((err) => {
            errF;
          });
      }
    </script>
  </body>
</html>

如果不指定method,则默认为get请求方式

3.2.2 请求方式别名

取别名其实就是对axios(config)的封装,主要是用来简化发送请求的操作

(1)axios.request(config)
(2)axios.get(url[, config])
(3)axios.post(url[, data][, config])
(4)axios.delete(url[, config])
(5)axios.put(url[, data][, config])
(6)axios.patch(url[, data][, config])

简化发送请求只是让请求方式的类型更明显,然后单独拎出来一两个配置项罢了,其他该配置的还是要进行配置


post、put、patch请求都是将data配置项单独拎出来的,这里这个data就单独占一个参数位置,你要么将data直接用{数据}的形式放在式子中,例如axios.post(url,{数据},{其他配置项}),要么在外边先用对象类型变量封装好数据let data = {数据},再将这个变量放在式子中axios.post(url,data,{其他配置项})
而像get、delete、request请求一般要么将请求数据放在url中,要么就在conifg中的param配置项中进行配置(配置完之后还是放在url)


put和patch请求都是用来更新数据的,但两者还是有区别滴,put会将完整的要更新的数据集传给后端进行数据的替换,注意是将数据全部替换哦,patch则是只将要更新的某个或某几个数据发给后端进行数据的局部更新,注意是在原有数据的基础上进行添加、删除、更新等操纵,也就是说不需要更新的数据就不动。

axios.get('/user?id=1&name=jack',{
	// 例如设置一个超时事件
	timeout:1000,
	// 设置一个响应类型
	responseType: 'json', 
	// ...
}).then().catch()

axios.post("/user",{
	// 要后台返回的数据类型
	responseType: 'json',
	// 基路径
	baseURL:"http://xxx",
	// ...
}).then().catch()

3.3 get和post传参

get请求

  • 方式一:参数以查询字符串格式直接写在url中
axios.get('/user?id=12345&name=user',
	// {其他配置项...}
	)
.then(function (res) {   
  console.log(res);
})
.catch(function (err) {  
  console.log(err);
});
  • 方式二:写在配置项params中,到时传过去时会自动按照查询字符串格式拼接到url后面
axios.get('/user', {  
   //params参数必写 , 如果没有参数传{}也可以    
   params: {         
	   id: 12345name: user   
   },
   // {其他配置项...}
})
.then(function (res) {
  console.log(res);
})
.catch(function (err) { 
  console.log(err);
});

post请求

  • 在配置项中传参,参数保存在请求体之中
var readyData={  
  id:1234,    
  name:user
};
axios.post("/notice",readyData,{其他配置项})
 .then((res) => {return res}) 
 .catch((err) => {return err})

3.4 执行多个并发请求

处理并发请求的助手函数
(1)axios.all(iterable),多个请求都完成是才会走下去
(2)axios.spread(callback)

// 请求一
function getUserAccount() {
  return axios.get('/user/12345');
}

// 请求二
function getUserPermissions() {
  return axios.get('/user/12345/permissions');
}

// 并发实现,调用all方法,参数是一个数组,数组的值为前面封装的axios
axios.all([getUserAccount(), getUserPermissions()])
  .then(axios.spread(function (acct, perms) {
    // 两个请求现在都执行完成,两个参数分别代表返回的结果
    // acct 表示请求一的结果
    // perms 表示请求二的结果
  }));

4、axios请求配置

4.1 配置内容

{
   // `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;
  }],

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

  // `params` 是即将与请求一起发送的 URL 参数,也就是说,到时参数会以查询字符串形式显示在url中
  // 必须是一个无格式对象(plain object)或 URLSearchParams 对象
  // 如果后台服务器用是nodejs写的,那么可以通过res.query获取到参数
  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
  // 如果后台服务器用是nodejs写的,那么可以通过res.body获取到参数
  data: {
    firstName: 'Fred'
  },

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

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

  // `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', // default

  // `responseEncoding` indicates encoding to use for decoding responses
  // Note: Ignored for `responseType` of 'stream' or client-side requests
  responseEncoding: 'utf8', // default

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

  // `xsrfHeaderName` is the name of the http header that carries the xsrf token value
  xsrfHeaderName: 'X-XSRF-TOKEN', // default

   // `onUploadProgress` 允许为上传处理进度事件
  onUploadProgress: function (progressEvent) {
    // Do whatever you want with the native progress event
  },

  // `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 >= 200 && status < 300; // default
  },

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

  // `socketPath` defines a UNIX Socket to be used in node.js.
  // e.g. '/var/run/docker.sock' to send requests to the docker daemon.
  // Only either `socketPath` or `proxy` can be specified.
  // If both are specified, `socketPath` is used.
  socketPath: null, // default

  // `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
  cancelToken: new CancelToken(function (cancel) {
  })
}

4.2 全局默认配置

作用:避免重复些相同的配置。

格式:

axios.default.xxx = 'xxx';

示例

axios.default.method = 'get'; // 设置默认的请求类型为get

axios.default.baseURL = 'http://localhost:3000/posts'; // 默认URL

配置的优先顺序
这个顺序是:在 lib/defaults.js 找到的库的默认值,然后是实例的 defaults 属性,最后是请求的 config 参数

5、响应结构

一个请求的响应包含以下信息

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

  // `status` 来自服务器响应的 HTTP 状态码
  status: 200,

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

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

  // `config` 是为请求提供的配置信息
  config: {},
  // 'request'
  // It is the last ClientRequest instance in node.js (in redirects)
  // and an XMLHttpRequest instance the browser
  request: {}
}
  • 使用
axios.get('/user/12345')
  .then(function(response) {
    console.log(response.data);
    console.log(response.status);
    console.log(response.statusText);
    console.log(response.headers);
    console.log(response.config);
  });

6、实例对象

6.1 创建实例对象

axios.create([config])

const obj = axios.create({
	baseURL:'http://localhost:3000',
	timeout:2000
})

6.2 使用实例

obj.get('/posts').then(response =>{
	console.log(response.data)
})

6.3 实例方法

指定的配置将与实例的配置合并。

axios#request(config)

axios#get(url[, config])

axios#delete(url[, config])

axios#head(url[, config])

axios#options(url[, config])

axios#post(url[, data[, config]])

axios#put(url[, data[, config]])

axios#patch(url[, data[, config]])

axios#getUri([config])

7、拦截器

7.1 使用拦截器

在请求或响应被 then 或 catch 处理前拦截它们。

// 设置请求拦截器
axios.interceptors.request.use(function (config) {
    // 在发送请求之前做些什么
    console.log("请求拦截器成功")
    
    return config;
  }, function (error) {
    // 对请求错误做些什么
    console.log("请求拦截器失败")
    
    return Promise.reject(error);
  });

// 设置响应拦截器
axios.interceptors.response.use(function (response) {
    // 2xx 范围内的状态码都会触发该函数。
    // 对响应数据做点什么
    console.log('响应拦截器成功')
    
    return response;
  }, function (error) {
    // 超出 2xx 范围的状态码都会触发该函数。
    // 对响应错误做点什么
    console.log('响应拦截器失败')
    
    return Promise.reject(error);
  });

// 发送请求
axios({
	method:'get',
	url:'http://localhost:3000/posts'
}).then(response => {
	console.log(response)
})

(1)执行顺序:请求拦截器(成功回调) =》 发送请求 =》响应拦截器(成功回调) =》 成功回调获取数据
但凡按照顺序执行下来后,有任意一个回调错了,那么往后都是失败回调
(2)如果添加多个拦截器,那么多个拦截器的执行顺序也是不同的,对于请求拦截器,先进的拦截器后执行,对于响应拦截器,先进的拦截器先执行

7.2 移除拦截器

const myInterceptor = axios.interceptors.request.use(function () {/*...*/});
axios.interceptors.request.eject(myInterceptor);

8、axios取消请求

主要借助到了axios中的cancelToken配置项

  • 方式一:使用 CancelToken.source 工厂方法创建 cancel token
const CancelToken = axios.CancelToken;
const source = CancelToken.source();

axios.get('/user/12345', {
  cancelToken: source.token
}).catch(function(thrown) {
  if (axios.isCancel(thrown)) {
    console.log('Request canceled', thrown.message);
  } else {
     // 处理错误
  }
});

axios.post('/user/12345', {
  name: 'new name'
}, {
  cancelToken: source.token
})

// 取消请求(message 参数是可选的)
source.cancel('Operation canceled by the user.');
  • 方式二:通过传递一个 executor 函数到 CancelToken 的构造函数来创建 cancel token:
cancelToken:new axios.CancelToken(function(c){
	// (3)将c的值赋值给cancel
	cancel = c;
}

示例

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <script src="../outerjs/axios.min.js"></script>
    <title>axios取消请求</title>
</head>
<body>
    <button class="button">发送请求</button>
    <button class="button">取消请求</button>
    <script>
        let btns = document.getElementsByClassName('button')

        // (1)声明一个变量(用来存储函数变量)
        let cancel = null;

        // 发送请求
        btns[0].onclick = function(){
            // 检测上一次请求是否已经完成(作用是为了避免用户重复点击导致占用太多资源)
            if(cancel !== null){
                // 如果上一次请求没有完成,那么就取消上一次的请求
                cancel()
            }

            axios.get('http://localhost:3000/posts',{
                // (2)添加配置对象的属性,传递一个构造函数创建cancel Token
                cancelToken:new axios.CancelToken(function(c){
                	// (3) 传递一个executor执行函数给cancel函数
                	cancel = c;
                })
            }).then(response => {
                console.log(response);

                // (4) 请求执行完之后将cancel值重置
                cancel = null;
            })
        }

        // 取消请求
        btns[1].onclick = function(){
            // 点击后取消请求
            cancel()
        }
    </script>
</body>
</html>

取消请求的原理如下:
1、new axios.CancelToken创建cancel token时,函数内部会准备一个promise对象,并将promiseresolve函数保存起来。
2、当执行外部定义的执行器函数时,将取消函数作为参数传递。取消请求函数的作用是执行时将promise指定为成功,值为Cancel对象。
3、当取消请求函数执行时(将promise修改成成功了),获取之前保存的promise状态;如果需要终止请求则会执行request.abort()中断请求,并调用reject(cancel对象)将发请求的promise状态改为失败

参考文档:
axios文档

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值