安装

$ npm i axios            // 阿西奥斯

引用 const axios = require('axios');

$ bower install axios

cdn <script src="http://unpkg.com/axios/dist/axios.min.js">

Request参数

{
    baseUrl: '/api'                    // 基础url
    url: '/databaseList',        // 请求的接口,与基础合起来为'/api/databaseList'
    method: 'get',        // 请求方式,default=get

    // 设置头部信息
    headers: {
        'Content-Type': 'Application-json',
        'X-token': '1k12hkj34j2kbjhs9df74b'},
    },

    // URL的参数,get或Content-Type='application/x-www-form-urlencoded'使用的参数,不能用data
    params: {
        ID: 12345
    },

    // data发送的主休,用于post、stream、buffer
    data: {
        username: 'sigunag',
        password: '*******'
    },

    // 超时时间
    timeout: 1000,

    // 响应类型,可以是 'arraybuffer', 'blob', 'document', 'json', 'text', 'stream'
    responseType: 'json',

    // 响应的编码
    responseEncoding: 'utf8',

    // socket代理路径
    socketPath: null, // default

    // keepAlive 保持连接,默认不启动
    httpAgent: new http.Agent({ keepAlive: true }),
    httpsAgent: new https.Agent({ keepAlive: true }),

    // 代理主机
    proxy: {
        host: '127.0.0.1',
        port: 9000,
        auth: {
            username: 'mikeymike',
            password: 'rapunz3l'
        }
    },

    // 取消请求
    cancelToken: new CancelToken(function (cancel) {

    })

    // 一个可选的函数负责序列化“参数”
    paramsSerializer: function(params) {
        return Qs.stringify(params, {arrayFormat: 'brackets'})
    },

    transformRequest: [function (data, headers) {        // 在请求服务器之前的回调,适用于post
        return data;
    }],
    transformResponse: [function (data) {        // 在响应的回调,适用于post
        return data;
    }],
}

Response参数

{
    // 响应数据
    data: {},

    // 状态码
    status: 200,

    // http响应状态消息
    statusText: 'OK',

    // 响应头
    headers: {},

    // `config` is the config that was provided to `axios` for the request
    config: {},

    // `request` is the request that generated this response
    // It is the last ClientRequest instance in node.js (in redirects)
    // and an XMLHttpRequest instance the browser
    request: {}
}

创建实例

const axios = require('axios');


const request = axios.create({
      baseURL: '/api',     // api的base_url
        timeout: 10000,     // 请求超时时间 ms
})

/* 创建拦截器 */
// 请求拦截器
request.interceptors.request.use(
    (config) => {
        // Do something before request is sent
        return config;
    }, 
  (error) => {
        // Do something with request error
        return Promise.reject(error);
    }
);

// 响应拦截器
request.interceptors.response.use(
    (response) => {
        // Do something with response data
        return response;
    }, 
    (error) => {
        // Do something with response error
        return Promise.reject(error);
    }
);

axios.get('/user', {        
    params: {
        ID: 12345
    }
})
.then((d) => {
    // success
})
.catch((error) => {
    // error
})
.then(() => {
    //
})


一、请求参数 

    1、get或content-type="application/x-www-form-urlencoded" 使用 params来加参数

    2、post、content-type="application/json" 使用 data来传参数

axios.all 处理多个请求

就是promis.all(),多个请求全部执行成功后在执行

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) {
        // Both requests are now complete
    }));

API

一、axios(config)

    1、post请求

        axios.request('/user/12345',{
            method: 'post',
            data: {
                firstName: 'Fred',
                lastName: 'Flintstone'
            }
        });

    2、get请求

        axios.request('http://bit.ly/2mTM3nY', {
            method:'get',
            responseType:'stream'
        })
        .then(function(response) {
            response.data.pipe(fs.createWriteStream('ada_lovelace.jpg'))
        });

二、创建实例

    const request = axios.create({
        baseURL: '/api',            // 基础
        timeout: 1000,                // 请求超时时间
        headers: {'X-Custom-Header': 'foobar'}
    });


{


}

axios-mock-adapter axios使用mock

https://github.com/ctimmerm/axios-mock-adapter