axios 异步请求,配置环境,请求配置,响应配置

axios 异步请求学习笔记

​ Axios 是一个基于promise网络请求库,作用于node.js浏览器中,它是 isomorphic 的(即同一套代码可以运行在浏览器和node.js中)。在服务端它使用原生node.js http模块, 而在客户端 (浏览端) 则使用XMLHttpRequests。

1、json-server的安装

​ 这个用于请求服务器建立,通过请求获取数据。

  1. 使用npm命令安装
npm install -g json-server
  1. 在项目的根目录下创建一个db.json,用于伪装数据
{
  "posts": [
    { "id": 1, "title": "json-server", "author": "typicode" }
  ],
  "comments": [
    { "id": 1, "body": "some comment", "postId": 1 }
  ],
  "profile": { "name": "typicode" }
}
  1. 启动json-server,使用命令
json-server --watch db.json
  1. 通过它提供的访问路劲进行访问,支持Restful风格的访问。

image-20211118141756389

2、安装axios

  1. 使用npm安装,通常在项目使用这个方式。
npm install axios
  1. 通过引入在线的CDN。
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>

3、axios的基本使用

3.1、发送Get请求

// 发出get请求
btn[0].onclick = function () {
    axios.get("http://localhost:3000/posts", // 第一个参数是请求的地址
              {
        id: 2,  // 第二个参数是请求携带的参数,通常以对象传入
    } 
             ).then(function (response) { // 请求成功的回调函数,返回数据会封装一个promise对象
        console.log(response);
    }).catch(error => { // 请求失败的回调函数,返回的数据会封装一个promise对象
        console.log(error);
    });
};

3.2、发送Post请求

btn[1].onclick = function () {
    axios.post("http://localhost:3000/posts", // 第一个参数是请求的地址
        {
            "title": "xiaotanke",
            "author": "xiaotanke"  // 第二个参数是请求携带的参数,通常以对象传入
        }
    ).then(response => { // 请求成功的回调函数,返回数据会封装一个promise对象
        console.log(response);
    }).catch(function (error) { // 请求失败的回调函数,返回的数据会封装一个promise对象
        console.log(error)
    });
};

3.3、通过配置axios发出请求

// 通过配置axios进行请求
btn[2].onclick = function () {
    // 进行请求,通过配置axios进行请求
    axios({
        method: "GET",  // 请求的方式,如果不指定方式,默认是GET请求
        url: "http://localhost:3000/posts", // 请求的地址
        data: {         // 请求的参数,通常是对象
            id: 1
        }
    }).then(response => { // 请求成功的回调函数,返回数据会封装一个promise对象
        console.log(response);
    }).catch(error => { // 请求失败的回调函数,返回的数据会封装一个promise对象
        console.log(error);
    });
};

4、response 响应对象

​ 如果请求成功,在响应成功的回调函数中会封装一个promise对象,这个对象中封装了请求的信息,响应数据的信息,响应头信息,封装的xmlHttpRequest信息等。

  1. config属性:是response的一个属性,这个属性值是一个对象

image-20211118155049482

  1. data属性:服务器响应的数据,它会将返回的数据自动转换成一个对象。

image-20211118155229335

  1. header属性:一些响应头的信息。

image-20211118155406439

  1. request属性:封装的一个XMLHttpRequest对象。

image-20211118155506829

  1. status属性:响应的状态码。

5、请求配置

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

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

  // `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 参数
  // 必须是一个无格式对象(plain object)或 URLSearchParams 对象
  // 就是在url后面追加参数,值是一个对象
  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` 是作为请求主体被发送的数据
  // 它可以有两个方式:字符串,对象
  // 如果是字符串,它就直接将字符串传递;如果是对象它会将对象装换成json字符串,然后传递。
  data: {
    firstName: 'Fred'
  },

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

   // `withCredentials` 表示跨域请求时是否需要使用cookie
   // false不携带,true携带
  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,默认为json

  // `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
  // (查看后面的 Cancellation 这节了解更多)
  cancelToken: new CancelToken(function (cancel) {
  })
}

axios的默认配置:

​ 可以通过axios.defaults.请求配置名 = 值,这个格式来设置默认的请求配置,例如以下:

axios.defaults.baseURL = 'http://localhost/'; // 可以配置默认的baseURL,将这段url会添加的请求路径中

6、axios创建实例进行请求

​ 通过创建axios实例设置不同的配置,可以对多个服务器进行发出请求。创建的axios实例的用法和axios本身这个对象一样。

// 创建一个axios实例
var myaxios = axios.create({
    baseURL: "http://localhost:3000",   // 设置这个实例的默认配置
    timeOut: 3000
});
// 通过实例对象进行请求
myaxios.get("/posts",{
    params: {
        id: 1
    }
}).then(response => {
    console.log(response.data[0]);
});var myaxios = axios.create({
    baseURL: "http://localhost",
    timeOut: 3000
});

7、取消请求

​ 如果用户疯狂点击一个请求的时候,但是上一个请求还未响应,这样就会造成服务器很大的压力,这就需要在用户多次点击请求的时候取消掉用户的上一次请求。

var CancelToken = axios.CancelToken;
// 通过配置axios进行请求
var  requested = null;
btn[2].onclick = function () {
    // 在请求前判断是否还存在请求
    if(requested !== null){
        // 将这个请求取消掉
        requested();
    }
    // 进行请求,通过配置axios进行请求
    axios({
        method: "get",  // 请求的方式
        url: "http://localhost:3000/posts", // 请求的地址
        data: {         // 请求的参数,通常是对象
            id: 1
        },
        cancelToken: new CancelToken(function executor(c) {
            // executor 函数接收一个 cancel 函数作为参数
            requested = c;
        })
    }).then(response => { // 请求成功的回调函数,返回数据会封装一个promise对象
        // 如果请求成功后,就需要将requested置为null
        requested = null;
        console.log(response);
    }).catch(error => { // 请求失败的回调函数,返回的数据会封装一个promise对象
        console.log(error);
    });
};
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值