Axios 模块学习笔记

390 阅读5分钟

Axios 模块学习笔记

基于promise可以用于浏览器和node.js的网络请求库。

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

安装模块: npm install axios

基本用例

为了在CommonJS中使用 require() 导入时获得TypeScript类型推断(智能感知/自动完成),请使用以下方法:

const axios = require('axios').default;

发起一个GET请求:

// Example1

axios.get('/user?ID=12345')
    .then(response => {
        // 处理成功
        console.log('处理成功:', response);  // 输出 response 响应对象
    }).catch(error => {
        console.log(error);
}).then(() => {
    console.log('总会执行!');
})

上述请求也可以按以下方式完成(可选):

axios.get('/user', { params: { ID: 12345 } })
.then(response => {
    console.log('成功响应', response);
})
.catch(error => {
    console.log('请求错误', error);
})
.then(() => {
    console.log('总是会执行!')
})

上述请求支持 async/await 语法:


async function getUser(){
    try{
        const response = await axios.get('/user?ID=12345');
        console.log(response);  // 如果没有出现错误,则输出 response
    }catch (err)
    {
        console.log(err);  // 如果抛出错误则被 try/catch 语句处理
    }
    console.log('总是会执行!');  // 无论正确错误,均会执行的语句.
}
getUser();

发起一个POST请求:

axios.post('/user', {
    firstName: 'Fred',
    lastName: 'Flintstone'
})
.then(response => {
    console.log('请求成功:', response);
})
.catch(error => {
    console.log('发生错误:', error);
})
.then(() => {
    console.log('总是会执行!');
});

发起多个并发请求

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

function getUserPermissions(){
    return axios.get('/user/123456/permissions');
}

Promise.all([getUserAccount(), getUserPermissions()])
.then(results => {
    const acct = results[0];
    const perm = results[1];
    console.log(acct, perm);
})

使用 Promis.all 函数 对 axios对象所返回的 Promise 对象进行统一管理.

Axios API

AxiosAPI

可以向 axios 传递相关配置来创建请求

axios(config)

axios({
    method: 'post',
    url: '/user/12345',
    data: {
        firsName: 'Fred',
        lastName: 'Flintstone'
    }
})

该请求已被发出,但没有任何 请求后的处理。

const fs = require('fs');
// 在 node.js 用GET请求获取远程图片
axios({
    method: 'get',
    url: '/image',
    responseType: 'stream'
})
.then(response => {
    response.data.pipe(fs.createWriteStream('axios_client.png'))
})

axios(url[, config])

// 发起一个GET请求(默认请求方式)
axios('/user/12345');

请求方式别名:

axios.request(config)

axios.request({
    url: '/user/12345',
    method: 'get',
}).then(response => {console.log(response.data)});

axios.get(url[, config])

axios.get('/user/12345').then(response => {console.log(response.data)});

axios.delete(url[, config])

axios.delete('/user/12345').then(response => {console.log(response.data)});

axios.head(url[, config])

axios.head('/user/12345').then(response => {console.log(response.headers)});

axios.options(url[, config])

axios.options('/user/12345').then(response => {console.log(response.data)});

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

axios.post('/user/12345').then(response => {console.log(response.data)});

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

axios.put('/user/12345').then(response => {console.log(response.data)});

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

axios.patch('/user/12345').then(response => {console.log(response.data)});

在使用别名方法时, urlmethoddata 这些属性都不必在配置中指定。

创建一个实例

您可以使用自定义配置新建一个实例。

axios.create([config])

const axios_obj = axios.create({
    baseURL: '/user/12345',
    timeout: 1000,
    headers: {'X-Custom-Header': 'foobar'}
});

实例方法

以下是可用的实例方法。指定的配置将与实例的配置合并。

axios#request(config)

axios_obj.request({}).then(response => console.log(response.data));
// 默认使用 get 方法,也可以给  request 方法中添加 method 属性,使其进行 POST 方法

axios_obj.request({method: 'post'}).then(response => console.log(response.data));

axios#get(url[, config])

axios_obj.get().then(response => console.log(response.data));
// 使用 .get 方法 在不传递参数时,默认等于传递: url = '', option = {}

axios#delete(url[, config])

axios_obj.delete().then(response => console.log(response.data));

axios#head(url[, config])

axios_obj.head().then(response => console.log(response.headers));

axios#options(url[, config])

axios_obj.options().then(response => console.log(response.data));

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

axios_obj.post().then(response => console.log(response.data));

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

axios_obj.put().then(response => console.log(response.data));

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

axios_obj.patch().then(response => console.log(response.data));

axios#getUri([config])

console.log(axios_obj.getUri());

请求配置

这些是创建请求时可以用的配置选项。只有 url 是必需的。如果没有指定 method,请求将默认使用 GET 方法。

const http = require('http');
const https = require('https');

const options = {
    // 1. url 是用于请求服务器的 URL  只有这个选项是必须的,它可以是绝对的URL 也可以是一个相对的URL地址
    url: '/user',
    // 2. method 是创建请求是使用的方法
    method: 'get',  // 默认值就是 'get' 请求方法

    // 3. baseURL 将自动添加在相对 url 前面,除非 url 是一个绝对的URL地址
    baseURL: 'https://www.xxx.com/api/',  // 最终的组合地址将为: https://www.xxx.com/api/user

    // 4. transformRequest 允许在向服务器发送前,修改请求数据
    // 它只能用于 PUT、POST、PATCH 这几个请求方法
    // 数组中最后一个函数必须返回一个字符串,一个 Buffer 实例 ArrayBuffer、FormData 或 Stream
    transformRequest: [function(data, headers){
        // 对发送的 data 进行转换处理
        return data; // 必须是一个Buffer、ArrayBuffer、FormData 或者 Stream流。
    }],

    // transformResponse 在传递给 then/catch 前,允许修改响应数据
    transformResponse: [function(data){
        // 对接收的 data 进行任意转换处理
    }],

    // 自定义请求头
    headers: {'X-Requested-With': 'XMLHttpRequest'},

    // params 是与请求一起发送的URL参数
    // 必须是一个简单对象 或者一个 URLSearchParams 对象
    params: {
        key1: 'value1',
        key2: '值2'
    },

    // data 是作为请求体被发送的数据
    // 在没有设置 `transformRequest` 时,则必须是以下类型之一:
    // - string, plain object, ArrayBuffer, ArrayBufferView, URLSearchParams
    // - 浏览器专属: FormData, File, Blob
    // - Node 专属: Stream, Buffer
    data: {
        firstName: 'Fred'
    },
    // 发送请求体数据的可选语法
    // 请求方式 post
    // 只有 value 会被发送,key 则不会
    // data: 'Country=Brasil&City=Belo Horizonte',

    // `timeout` 指定请求超时的毫秒数。
    // 如果请求时间超过 `timeout` 的值,则请求会被中断
    timeout: 1000, // 默认值是 `0` (永不超时)

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

    // `adapter` 允许自定义处理请求,这使测试更加容易。
    // 返回一个 promise 并提供一个有效的响应 (参见 lib/adapters/README.md)。
    adapter: function (config) {
        /* ... */
    },

    // `auth` HTTP Basic Auth
    auth: {
        username: 'janedoe',
        password: 's00pers3cret'
    },

    // `responseType` 表示浏览器将要响应的数据类型
    // 选项包括: 'arraybuffer', 'document', 'json', 'text', 'stream'
    // 浏览器专属:'blob'
    responseType: 'json', // 默认值

    // `responseEncoding` 表示用于解码响应的编码 (Node.js 专属)
    // 注意:忽略 `responseType` 的值为 'stream',或者是客户端请求
    // Note: Ignored for `responseType` of 'stream' or client-side requests
    responseEncoding: 'utf8', // 默认值

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

    // `xsrfHeaderName` 是带有 xsrf token 值的http 请求头名称
    xsrfHeaderName: 'X-XSRF-TOKEN', // 默认值

    // `onUploadProgress` 允许为上传处理进度事件
    // 浏览器专属
    onUploadProgress: function (progressEvent) {
        // 处理原生进度事件
    },

    // `maxContentLength` 定义了node.js中允许的HTTP响应内容的最大字节数
    maxContentLength: 2000,

    // `maxBodyLength`(仅Node)定义允许的http请求内容的最大字节数
    maxBodyLength: 2000,

    // `validateStatus` 定义了对于给定的 HTTP状态码是 resolve 还是 reject promise。
    // 如果 `validateStatus` 返回 `true` (或者设置为 `null` 或 `undefined`),
    // 则promise 将会 resolved,否则是 rejected。
    validateStatus: function (status) {
        return status >= 200 && status < 300; // 默认值
    },

    // `maxRedirects` 定义了在node.js中要遵循的最大重定向数。
    // 如果设置为0,则不会进行重定向
    maxRedirects: 5, // 默认值

    // `socketPath` 定义了在node.js中使用的UNIX套接字。
    // e.g. '/var/run/docker.sock' 发送请求到 docker 守护进程。
    // 只能指定 `socketPath` 或 `proxy` 。
    // 若都指定,这使用 `socketPath` 。
    socketPath: null, // default

    // ' httpAgent '和' httpAgent '定义了执行http时使用的自定义代理
    //和HTTPS请求,分别在node.js中。这允许像这样添加选项
    //默认情况下未启用的keepAlive。
    httpAgent: new http.Agent({ keepAlive: true }),
    httpsAgent: new https.Agent({ keepAlive: true }),

    // `proxy` 定义了代理服务器的主机名,端口和协议。
    // 您可以使用常规的`http_proxy` 和 `https_proxy` 环境变量。
    // 使用 `false` 可以禁用代理功能,同时环境变量也会被忽略。
    // `auth`表示应使用HTTP Basic auth连接到代理,并且提供凭据。
    // 这将设置一个 `Proxy-Authorization` 请求头,它会覆盖 `headers` 中已存在的自定义 `Proxy-Authorization` 请求头。
    // 如果代理服务器使用 HTTPS,则必须设置 protocol 为`https`
    proxy: {
        protocol: 'https',
        host: '127.0.0.1',
        port: 9000,
        auth: {
            username: 'mikeymike',
            password: 'rapunz3l'
        }
    },
    // ' decompress '表示是否应该解压响应体
    // 自动。如果设置为' true '也会删除'content-encoding'标题
    // 所有解压缩响应的响应对象
    // - Node (XHR不能关闭解压)
    decompress: true // 默认值
}
console.log(Stream);

响应结构

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

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

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

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

    // `headers` 是服务器响应头
    // 所有的 header 名称都是小写,而且可以使用方括号语法访问
    // 例如: `response.headers['content-type']`
    headers: {},

    // `config` 是 `axios` 请求的配置信息
    config: {},

    // `request` 是生成此响应的请求
    // 在node.js中它是最后一个ClientRequest实例 (in redirects),
    // 在浏览器中则是 XMLHttpRequest 实例
    request: {}
}

当使用 then 时,您将接收如下响应:

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);
    });

默认配置

您可以指定默认配置,它将作用于每个请求。

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';
// 仅POST请求才设置该请求头

自定义实例默认值:

// 创建实例时配置默认值 
const instance = axios.create({ baseURL: 'https://api.example.com' });
// 创建实例后修改默认值 
instance.defaults.headers.common['Authorization'] = AUTH_TOKEN;

配置将会按优先级进行合并。它的顺序是:

默认值,然后是实例的 defaults 属性,最后是请求的 config 参数。后面的优先级要高于前面的。下面有一个例子。

// 使用库提供的默认配置创建实例
// 此时超时配置的默认值是 `0`
const instance = axios.create();

// 重写库的超时默认值
// 现在,所有使用此实例的请求都将等待2.5秒,然后才会超时
instance.defaults.timeout = 2500;

// 重写此请求的超时时间,因为该请求需要很长时间
instance.get('/longRequest', {
    timeout: 5000
});

拦截器

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

// 添加请求拦截器
axios.interceptors.request.use(function (config) {
    // 在发送请求之前做些什么
    return config;
}, function (error) {
    // 对请求错误做些什么
    return Promise.reject(error);
});

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

如果你稍后需要移除拦截器,可以这样:

const myInterceptor = axios.interceptors.request.use(function () {/*...*/}); 
// 返回拦截器ID
axios.interceptors.request.eject(myInterceptor);

可以给自定义的 axios 实例添加拦截器。

const instance = axios.create(); 
instance.interceptors.request.use(function () {/*...*/});

错误处理

axios.get('/user/12345')
    .catch(function (error) {
        if (error.response) {
            // 请求成功发出且服务器也响应了状态码,但状态代码超出了 2xx 的范围
            console.log(error.response.data);
            console.log(error.response.status);
            console.log(error.response.headers);
        } else if (error.request) {
            // 请求已经成功发起,但没有收到响应
            // `error.request` 在浏览器中是 XMLHttpRequest 的实例,
            // 而在node.js中是 http.ClientRequest 的实例
            console.log(error.request);
        } else {
            // 发送请求时出了点问题
            console.log('Error', error.message);
        }
        console.log(error.config);
    });
// 通过对 error 对象的 request、response 属性进行判断,即可以分析 错误出现在哪个环节.

使用 validateStatus 配置选项,可以自定义抛出错误的 HTTP code。

axios.get('/user/12345', {
    validateStatus: function (status) {
        return status < 500; // 处理状态码小于500的情况
    }
})

从 v0.22.0 开始,Axios 支持以 fetch API 方式—— AbortController 取消请求:

const controller = new AbortController();

axios.get('/foo/bar', {
    signal: controller.signal
}).then(function(response) {
    //...
});
// 取消请求
controller.abort()

请求体编码

默认情况下,axios将 JavaScript 对象序列化为 JSON 。 要以application/x-www-form-urlencoded格式发送数据,您可以使用以下选项之一。

浏览器

在浏览器中,可以使用URLSearchParams API,如下所示:

const params = new URLSearchParams();
params.append('param1', 'value1');
params.append('param2', 'value2');
axios.post('/foo', params);

使用 URLSearchParams 应该注意,在 火狐 浏览器中 57.x.x 版前,单引号'将被转义.

Node.js

在 node.js 中, 可以使用 querystring 模块,如下所示:

const querystring = require('querystring');
axios.post('http://something.com/', querystring.stringify({ foo: 'bar' }));

或者从url module中使用URLSearchParams如下所示:

const url = require('url');
const params = new url.URLSearchParams({ foo: 'bar' });
axios.post('http://something.com/', params.toString());

Form data

在 node.js, 您可以使用 form-data库,如下所示:

const FormData = require('form-data');

const form = new FormData();
form.append('my_field', 'my value');
form.append('my_buffer', new Buffer(10));
form.append('my_file', fs.createReadStream('/foo/bar.jpg'));

axios.post('https://example.com', form, { headers: form.getHeaders() })

或者, 使用一个拦截器:

axios.interceptors.request.use(config => {
    if (config.data instanceof FormData) {
        Object.assign(config.headers, config.data.getHeaders());
    }
    return config;
});

完结!