axios

创建实例

诚然,对于简单的GET和POST请求,只需要设置一个目标URL和对应的HTTP请求体即可:

import axios from 'axios';
axios.get('http://192.168.0.150:80/about')
      .then(response => {
            console.log(response.data);
      });
axios.post('http://192.168.0.150:80/auth', { name: 'develon', password: '123456' })
      .then(response => {});

但是对于同一类请求,通常需要配置,可以创建一个axios实例,将通用配置进行抽象。
请看axios与实例相关的接口:

export interface AxiosStatic extends AxiosInstance {
  create(config?: AxiosRequestConfig): AxiosInstance;
  Cancel: CancelStatic;
  CancelToken: CancelTokenStatic;
  isCancel(value: any): boolean;
  all<T>(values: (T | Promise<T>)[]): Promise<T[]>;
  spread<T, R>(callback: (...args: T[]) => R): (array: T[]) => R;
}
  • example: 创建固定URL的axios实例 API
const API = axios.create('http://192.168.0.150:80');
API.post('/login', { name: 'develon', password: '123456' })
      .then(response => {});

axios本身是一个函数,get post等是别名

axios本身是一个wrap函数,可以通过将相关配置传递给axios来发出请求。

import axios from 'axios';

// axios(url[, config]) 默认发出GET请求
axios("http://192.168.0.150", { hreaders: {} }).then(response => {});

// axios(config) 在config中指定method等指标
axios({
    method: 'POST',
    url: "http://192.168.0.150/auth",
    data: { name: 'develon', password: '123456' },
}).then(response => {});

axios.get、axios.post、axios.head、axios.options等静态方法其实都是axios函数的别名。
使用别名方法时,就无需再在config中指定url,method和data属性了。

响应

axios.get('/user/12345')
  .then(response => {
    console.log(response.data);
    console.log(response.status);
    console.log(response.statusText);
    console.log(response.headers);
    console.log(response.config); // 发送请求时的相应配置
  });

默认配置

全局默认值

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';

自定义实例默认值

// 创建实例时设置配置默认值
const instance = axios.create({
  baseURL: 'https://api.example.com'
});

// 创建实例后更改默认值
instance.defaults.headers.common['Authorization'] = AUTH_TOKEN;

合并配置顺序

对于每个请求,所有配置将被合并,顺序为:lib/defaults.js、全局或自定义实例默认值、请求时的config。

拦截器

可以拦截请求或响应,再请求发出之前和响应之前进行处理。

// Add a request interceptor
axios.interceptors.request.use(function (config) {
    // Do something before request is sent
    return config;
  }, function (error) {
    // Do something with request error
    return Promise.reject(error);
  });

// Add a response interceptor
axios.interceptors.response.use(function (response) {
    // Any status code that lie within the range of 2xx cause this function to trigger
    // Do something with response data
    return response;
  }, function (error) {
    // Any status codes that falls outside the range of 2xx cause this function to trigger
    // Do something with response error
    return Promise.reject(error);
  });

可以存储use函数返回值,以便可以删除拦截器:

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

取消请求

使用HTTP代理

存在NDS污染问题。

  proxy: {
    host: '127.0.0.1',
    port: 9000,
    auth: {
      username: 'mikeymike',
      password: 'rapunz3l'
    }
  },

END

posted @ 2020-11-05 10:04  develon  阅读(140)  评论(0编辑  收藏  举报