Axios使用操作
Axios 是什么?
Axios 是一个基于promise网络请求库,作用于node.js 和浏览器中。 它是 isomorphic 的(即同一套代码可以运行在浏览器和node.js中)。在服务端它使用原生 node.js http 模块, 而在客户端 (浏览端) 则使用 XMLHttpRequests。
特性
- 从浏览器创建 XMLHttpRequests
- 从 node.js 创建 http 请求
- 支持 promise API
- 拦截请求和响应
- 转换请求和响应数据
- 取消请求
- 自动转换JSON数据
- 客户端支持防御XSRF
安装
使用 npm:
$ npm install axios
使用 bower:
$ bower install axios
使用 yarn:
$ yarn add axios
使用 jsDelivr CDN:
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
使用 unpkg CDN:
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
基本发送请求用例
发起个get请求
// 引入aixos
import axios from 'axios';
//const axios = require('axios');
// 向给定ID的用户发起请求
//第一种get请求方式
aixos.get('/xxx?id=123213').then(response=>{
// 处理成功情况
console.log(response);
},error=>{
// 处理失败情况
console.log(error);
}).catch(error){
// 处理错误情况或代码异常
console.log(error);
}.then(data=>{
// 总是会执行
})
//第二种get请求方式
aixos.get('/xxxx',{
id:123
}).then(response=>{
// 处理成功情况
console.log(response);
},error=>{
// 处理失败情况
console.log(error);
}).catch(error){
// 处理错误情况或代码异常
console.log(error);
}
// 支持async/await用法
async function getUser() {
//try 代码异常,但不影响下面代码执行
try {
const response = await axios.get('/xxx?id=123');
// 处理成功情况
console.log(response);
} catch (error) {
// 处理错误情况或代码异常
console.error(error);
}
}
//注意 .then 中的error是处理请求失败情况,.catch 是处理请求失败或代码出错而抛出的错误
发起个post请求
// post 有一种方式,其他地方换个get都是差不多的,就请求方式不一样
axios.post('/xxx', {
username: 'Fred',
userpassword: 'Flintstone'
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
Axios API
可以向 axios 传递相关配置来创建请求
axios({
url:'/xxx',/*请求地址*/,
method:'GET',/*请求方式 (get/post),默认为get方式*/
params:{
id:123,
},/*get方式发起请求,通过params传参数*/
data:{
id:123,
},/*仅适用 'PUT', 'POST', 'DELETE 和 'PATCH' 请求方法,通过data传参数*/
// `baseURL` 将自动加在 `url` 前面,除非 `url` 是一个绝对 URL。
// 它可以通过设置一个 `baseURL` 便于为 axios 实例的方法传递相对 URL
baseURL: 'https://some-domain.com/api/',
// `transformRequest` 允许在向服务器发送前,修改请求数据
// 它只能用于 'PUT', 'POST' 和 'PATCH' 这几个请求方法
// 数组中最后一个函数必须返回一个字符串, 一个Buffer实例,ArrayBuffer,FormData,或 Stream
// 你可以修改请求头。
transformRequest: [function (data, headers) {
// 对发送的 data 进行任意转换处理
return data;
}],
// `transformResponse` 在传递给 then/catch 前,允许修改响应数据
transformResponse: [function (data) {
// 对接收的 data 进行任意转换处理
return data;
}],
// 自定义请求头
headers: {'X-Requested-With': 'XMLHttpRequest'},
// `timeout` 指定请求超时的毫秒数。
// 如果请求时间超过 `timeout` 的值,则请求会被中断
timeout: 1000, // 默认值是 `0` (永不超时)
// `withCredentials` 表示跨域请求时是否需要使用凭证
withCredentials: false, // default
// `responseType` 表示浏览器将要响应的数据类型
// 选项包括: 'arraybuffer', 'document', 'json', 'text', 'stream'
// 浏览器专属:'blob'
responseType: 'json', // 默认值
// 浏览器专属
onUploadProgress: function (progressEvent) {
// 处理原生进度事件
},
// `onDownloadProgress` 允许为下载处理进度事件
// 浏览器专属
onDownloadProgress: function (progressEvent) {
// 处理原生进度事件
},
// `maxContentLength` 定义了node.js中允许的HTTP响应内容的最大字节数
maxContentLength: 2000,
// `maxBodyLength`(仅Node)定义允许的http请求内容的最大字节数
maxBodyLength: 2000,
// `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'
}
},
}).then(response=>{
//成功
}).catch(error=>{
//错误
})
请求方式别名
- 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]])
发起多个请求
function getBanner(config){
/*返回值为proimse对象*/
return axios(config/*配置*/);
}
function getHotData(config){
/*返回值为proimse对象*/
return axios(config/*配置*/);
}
// axios.all只要有一个错误,则抛出错误后不会继续请求了
axios.all([getBanner({}),getHotData({})]/*以数组的方式,执行函数接收返回值*/).then(response=>{
//response 为数组是每个请求的数据 response [xxx,xxx];
// 成功
}).catch(error=>{
// 失败
})
Axios 实例
创建一个实例
您可以使用自定义配置新建一个实例。axios.create([config])
const instance = axios.create({
baseURL: 'https://some-domain.com/api/',
timeout: 1000,
headers: {'X-Custom-Header': 'foobar'}
});
实例方法
- 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]])
- axios#getUri([config])
例如
const instance = axios.create({
baseURL: 'https://some-domain.com/api/',
timeout: 1000,
headers: {'X-Custom-Header': 'foobar'}
});
instance.get('/banner',{
type:'pc'
}).then(response=>{
console.log(response);
}).catch(error=>{
console.error(error);
})
默认配置
全局
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';
局部
axios({
baseURL:'https://api.example.com',
})