Vue talks about axios

Table of contents


Introduction to axios

1. Installation

2. Configuration path

3. Interpretation of axios files

import:

export:

Execute the post request (the request execution method of get is obtained in the same way):

Execute multiple concurrent requests:

Request configuration (Axios Chinese use - short book (jianshu.com)):

Response structure:

The structure of the request interceptor and the corresponding interceptor (here only the structure of the request interceptor):


Introduction to axios

Axios is a promise-based HTTP library that can be used in the browser and node.js.

1. Installation

1. Use npm to install   npm install axios --save
2. Use bower to install   bower install axios --save
3. Use CDN to import directly  <script src="https://unpkg.com/axios/dist/axios.min.js"></script>

2. Configuration path

The basic path configurations such as baseServer, baseServerPort, and baseURL can be defined in config.js. It can be imported directly on axios.js to improve the code reusability of the project.

3. Interpretation of axios files

import and export: A module is an independent file, and all variables inside the file cannot be obtained from the outside. If you want to obtain a certain variable, you must export it through export and import it through import.

import:

import axios from 'axios';
import {
    baseURL
} from '@/config.js';
import router from "../router";

export:

Create axios custom instance defaults

Note that the Axios instance is the one to be applied to the axios file

export const Axios = axios.create({
    timeout: 10 * 1000,
});

Execute the post request (the request execution method of get is obtained in the same way):

  axios({
        method: 'post',
        url: url,
        data: data,
        headers: {
        },
      })
        .then((response) => {
        })
        .catch((error) => {
        });

Execute multiple concurrent requests:

function getUserAccount() {
  return axios.get('/user/12345');
}
function getUserPermissions() {
  return axios.get('/user/12345/permissions');
}
axios.all([getUserAccount(), getUserPermissions()])
  .then(axios.spread(function (acct, perms) {
    // 两个请求现在都执行完成
  }));

Request configuration ( Axios Chinese use - Jianshu (jianshu.com) ):

{
  url: '/user',
  method: 'get', // 默认是 get
  baseURL: 'https://some-domain.com/api/',
  transformRequest: [function (data) {
    return data;
  }],
  transformResponse: [function (data) {
    // 对 data 进行任意转换处理
    return data;
  }],

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

  // `params` 是即将与请求一起发送的 URL 参数
  // 必须是一个无格式对象(plain object)或 URLSearchParams 对象
  params: {
    ID: 12345
  },

  // `paramsSerializer` 是一个负责 `params` 序列化的函数
  paramsSerializer: function(params) {
    return Qs.stringify(params, {arrayFormat: 'brackets'})
  },

  data: {
    firstName: 'Fred'
  },

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

  // `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', // 默认的

  // `responseEncoding`表示用于响应的编码
  // 注意: 当responseType是stream时或者client-side请求时,配置无效
  responseEncoding: 'utf8', // 默认的

  // `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 将被 resolved; 否则,promise 将被 rejected
  validateStatus: function (status) {
    return status >= 200 && status < 300; // 默认的
  },

  maxRedirects: 5, // 默认的

  socketPath: null, // 默认的

  // `httpAgent` 和 `httpsAgent` 分别在 node.js 中用于定义在执行 http 和 https 时使用的自定义代理。允许像这样配置选项:
  // `keepAlive` 默认没有启用
  httpAgent: new http.Agent({ keepAlive: true }),
  httpsAgent: new https.Agent({ keepAlive: true }),

  // 'proxy' 定义代理服务器的主机名称和端口
  proxy: {
    host: '127.0.0.1',
    port: 9000,
    auth: : {
      username: 'mikeymike',
      password: 'rapunz3l'
    }
  },


  cancelToken: new CancelToken(function (cancel) {
  })
}

Response structure:

{
  // `data` 由服务器提供的响应
  data: {},
  // `status` 来自服务器响应的 HTTP 状态码
  status: 200,
  // `statusText` 来自服务器响应的 HTTP 状态信息
  statusText: 'OK',
  // `headers` 服务器响应的头
  headers: {},
  // `config` 是为请求提供的配置信息
  config: {}
}

The structure of the request interceptor and the corresponding interceptor (here only the structure of the request interceptor):

The role is to intercept requests or responses before they are processed by then or catch

//请求拦截器
Axios.interceptors.request.use(config => {
    //若存在这样的token,则从本地存储取出
    if (localStorage.token) {
        config.headers.Authorization = localStorage.getItem("token")
    }

    if (localStorage.intranetURL) {
        config.url = localStorage.getItem("intranetURL") + config.url
    } else {
        config.url = baseURL + config.url
    }
    console.log(config.url)

    return config
}, error => {
    return Promise.reject(error)
});

Global registration of axios:

Use the install (vue) method to register Axios globally, and the Axios instance can be reused globally!

export default {
    install(Vue) {
        Object.defineProperty(Vue.prototype, '$Axios', {
            value: Axios
        })
    }
}

Guess you like

Origin blog.csdn.net/ikkkp/article/details/123999022