axios知识点回顾

建议

我这里只是列出了一些简单的知识点,方便我的记忆回顾。

建议看 sass 官方文档,里面的内容更加详细和完善,内容也是最新的,网址:https://www.axios-http.cn/docs/intro。

安装

使用 npm:$ npm install axios

使用 cdn:<script src="https://unpkg.com/axios/dist/axios.min.js"></script>(可以在 https://www.bootcdn.cn/ 网站去获取 cdn)

使用 bower:$ bower install axios

使用 yarn:yarn add axios

引入 axios

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

const axios = require('axios').default

axios.<method> 能够提供自动完成和参数类型推断功能

GET 请求

GET 请求的参数可以跟在 url 后面,如:?name='张三'&age=18 。也可以放在第二个参数位,使用 params 请求体,以键值对的形式进行请求。

// 为给定 ID 的 user 创建请求
axios.get('/user?ID=12345')

axios.get('/user', {
params: {
ID: 12345
}
})

axios.get().then().catch()

// 支持async/await用法
async function getUser() {
// 抛出异常
try {
const response = await axios.get('/user?ID=12345')
} catch (err) {
console.error(err)
}
}

POST 请求

POST 请求只能在第二个参数位,以键值对的形式进行请求。

axios.post('/user', {}).then().catch()

执行多个并发请求

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

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

axios.all([getUserAccount(), getUserPermissions()]).then()

axios API

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

**语法**:axios(config) (config:配置对象)

**语法**:axios(url[, config])(默认是发送 GET 请求)

// 发送 POST 请求
axios({
// 请求类型
method: 'post',
// URL
url: '/user/12345',
// 请求体
data: {
firstName: 'Fred',
lastName: 'Flintstone'
}
}).then()

// 发送 GET 请求(获取远端图片)
axios({
method:'get',
url:'http://bit.ly/2mTM3nY',
responseType:'stream'
}).then()

并发

处理并发请求的函数

axios.all(iterable)

axios.spread(callback)

建实例对象

可以使用自定义配置新建一个 axios 实例。axios.create([config])

语法:

// 创建一个实例对象 test
const test = axios.create({
// 基础 url
baseURL: 'http://127.0.0.1:8000',
// 超时时间
timeout: 1000,
// 携带的请求头
headers: {'X-Custom-Header': 'foobar'}
});
// 这里的 test 与 axios 对象的功能类似

// 使用创建的实例对象
test({ url: '/server' }).then()
// 与上面的使用效果一样
test.get('/server').then()

实例方法:

axios.request(config)

axios.get(url[, config])

axios.delete(url[, config])

axios.head(url[, config])

axios.options(url[, config])

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

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

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

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

// axios.request(config)
axios.request({
method: 'GET',
url: ''
}).then()

// axios.post(url[, data[, config]])
axios.post('url',{}).then()

请求配置

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

{
url: '/user',
method: 'get', // 默认值
// `baseURL` 将自动加在 `url` 前面,除非 `url` 是一个绝对 URL。
baseURL: 'https://some-domain.com/api/',
// 自定义请求头
headers: {'X-Requested-With': 'XMLHttpRequest'},
// `timeout` 指定请求超时的毫秒数。
timeout: 1000, // 默认值是 `0` (永不超时)
// `params` 是与请求一起发送的 URL 参数
params: {
ID: 12345
},

// `data` 是作为请求体被发送的数据
// 仅适用 'PUT', 'POST', 'DELETE 和 'PATCH' 请求方法
data: {
firstName: 'Fred'
},

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

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

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

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

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

// `onDownloadProgress` 允许为下载处理进度事件
// 浏览器专属
onDownloadProgress: function (progressEvent) {
// 处理原生进度事件
},
// `proxy` 定义了代理服务器的主机名,端口和协议。
proxy: {
// 代理服务器使用 HTTPS,则必须设置 protocol 为`https`
protocol: 'https',
host: '127.0.0.1',
port: 9000,
auth: {
username: 'mikeymike',
password: 'rapunz3l'
}
},

}

响应结构

服务器返回的响应信息:

{
data: {},
status: 200,
statusText: 'OK',

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

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

// `request` 是生成此响应的请求
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 默认配置:

// 请求基础url
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;
// 原请求方式
axios({
method:'GET',
url:'http://127.0.0.1:8000/server',
data:{
xxx
}
).then()

// 现请求方式
// 设置默认的请求方式为 GET
axios.default.method = 'GET'
// 设置默认的请求路径
axios.default.baseURL = 'http://127.0.0.1:8000'
// 设置默认的请求 url 参数
axios.default.params = {id:100}
// 设置默认的超时时间
axios.default.timeout = 3000

拦截器

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

// 设置请求拦截器
// config 配置对象
axios.interceptors.request.use(function (config) {
// 在发送请求之前做些什么
// 可以修改 config 中的参数
return config;
}, function (error) {
// 对请求错误做些什么
return Promise.reject(error);
});

// 设置响应拦截器
axios.interceptors.response.use(function (response) {
// 对响应数据做点什么
return response;
}, function (error) {
// 对响应错误做点什么
return Promise.reject(error);
})

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

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

可以为自定义 axios 实例添加拦截器

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