一、安装(任选下面一种方式进行安装)
npm install axios
bower install axios
yarn add axios
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
二、使用
1、导入: 如果是使用命令行安装完 axios ,需在项目中引入 axios(直接使用 script 标签忽略该步骤)
// 在 CommonJS 中使用 axios 需要用 require() 进行导入
const axios = require('axios').default
// 在 ESM 中使用 axios 需要使用 import 进行导入
import axios from 'axios'
2、基本使用
① get 请求
let userId = 123
axios.get('/userinfo?id=' + userId).then(res => {}).catch(err => {})
axios.get('/userinfo', {
params: {id: userId}
}).then(res => {}).catch(err => {})
② post 请求
let data = {
name: 'bob',
age: 11
}
axios.post('/setUserinfo', data).then(res => {}).catch(err => {})
③ 多个并发请求
const request1 = axios.get('/getUserName')
const request2 = axios.get('/getUserAge')
Promise.all([request1, request2]).then(res => {
console.log(res[0], res[1])
})
④ axios 通用配置请求
axios({
baseURL: 'xxxx',
url: '/xxxx',
method: 'get',
data: {}, // 仅仅 post、put、patch、delete方法可用
params: {}, // 紧跟在 url 上的参数
headers: {
'Content-Type': 'application/json'
},
timeout: 60000, // 毫秒
responseType: 'json', // 后台响应过来数据的类型
responseEncoding: 'utf8', // 后台响应过来的数据的编码
onUploadProgress: function(){}, // 上传处理进度事件
onDownloadProgress: function(){}, // 下载进度事件
maxContentLength: 2000, // nodejs 允许的响应内容大小
maxBodyLength: 2000, // nodejs 允许请求的数据大小
maxRedirects: 5, // nodejs 中最大重定向的次数
cancelToken: new CancelToken(function(cancel){}), // 取消请求
withCredentials: false, // 跨域是否需要凭证
auth: {}, // http basic auth
xsrfCookieName: 'XSRF-TOKEN',
xsrfHeaderName: 'X-XSRF-TOKEN',
proxy: {}, // 代理配置
transformRequest: [], // 发送请求前,用于修改发送的请求数据
transformResponse: [], // 在 then / catch 接收到响应数据时,对响应数据进行修改
paramsSerializer: function(params){}, // 用于对 params 进行序列化
validateStatus: function(stataus){}, // 用于 http 状态码是 resolve 还是 reject
socketPath: null, // 在 nodejs 中使用的 UNIX 套接字
decompress: true // response body 是否反编译
})
⑤ 请求别名
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 实例
const axiosInstance = axios.create({
baseURL: 'http://xxxxx',
timeout: 60000, // 毫秒
headers: {
'Content-Type': 'application/json'
}
})
⑦ 设置 axios 全局静态配置
axios.defaults.baseURL = 'http://xxxxx'
axios.defaults.headers['Content-Type'] = 'application/json'
// 优先级:config 中的配置 > axios 实例中的配置 > axios 全局静态配置
⑧ 请求拦截器 axio.interceptors.request.use()
const requestInterceptor = axios.interceptors.request.use(function(config){
return config
}, function(error){
return Promise.reject(error)
})
// 拦截器移除
axios.interceptors.request.eject(requestInterceptor)
⑨ 响应拦截器 axios.interceptors.response.use()
const responseInterceptor = axios.interceptors.response.use(function(response){
return response
}, function (error){
return Promise.reject(error)
})
// 拦截器移除
axios.interceptors.response.eject(responseInterceptor)
⑩ 取消请求
// vue 项目中
<template>
<button @click="startRequest">开始请求</button>
<button @click="stopRequest">中断请求</button>
</template>
<script>
import axios from 'axios'
export deafult{
data() {
return {
CancelToken: null,
source: null
}
},
methods: {
// 开始请求
startRequest() {
this.CancelToken = axios.CancelToken
this.source = this.CancelToken.source()
axios.get('http://10.20.3.15:3000/getTable?page=1&size=100', {
cancelToken: this.source.token,
}).catch(err => {
if (axios.isCancel(err)) {
console.lgo('cancel', err)
}
})
},
// 中断请求
stopRequest() {
this.source.cancel('i want to cancel')
},
}
}
</script>
⑪ 请求数据的编码方式
// axios 的 post 请求时, 当需将请求的数据转为 JSON 格式
axios.deafult.headers['Content-Type'] = 'application/json'
let data = {id: 1, num: 12}
axios.post('/postxxxx', data)
// axios 的 post 请求时, 当需将请求的数据转为 FormData 格式 - 在支持 URLSearchParams 的浏览器中
axios.deafult.headers['Content-Type'] = 'application/x-www-form-urlencoded'
const data = new URLSearchParams() // 在浏览器中可以使用这个,但不是所有浏览器都支持
data.append('id', 1)
data.append('num', 12)
axios.post('/postxxxx', data)
// axios 的 post 请求时, 当需将请求的数据转为 FormData 格式 - 在不支持 URLSearchParams 的浏览器中可以使用 qs 库
axios.deafult.headers['Content-Type'] = 'application/x-www-form-urlencoded'
const qs = require('qs') // 或者使用 import qs from 'qs'
const data = qs.stringify({id: 1, num: 12})
axios.post('/postxxxx', data)
// axios 的 post 请求时, 当需将请求的数据转为 FormData 格式 - 在 nodejs 中可以使用 querystring 模块
axios.deafult.headers['Content-Type'] = 'application/x-www-form-urlencoded'
const querystring = require('querystring')
const data = querystring.stringify({id: 1, num: 12})
axios.post('/postxxxx', data)
// axios 的 post 请求时, 当需将请求的数据转为 FormData 格式 - 在 nodejs 中可以使用 url 模块
axios.deafult.headers['Content-Type'] = 'application/x-www-form-urlencoded'
const url = require('url')
const data = new url.URLSearchParams({id: 1, num: 12})
axios.post('/postxxxx', data)
// axios 的 post 请求时, 当需将请求的数据转为 FormData 格式 - 在 nodejs 中可以使用 qs 库
axios.deafult.headers['Content-Type'] = 'application/x-www-form-urlencoded'
const qs = require('qs')
const data = qs.stringify({id: 1, num: 12})
axios.post('/postxxxx', data)
// axios 的 post 请求时, 当需将请求的数据转为 FormData 格式 - 在 nodejs 中可以使用 form-data 库
axios.deafult.headers['Content-Type'] = 'application/x-www-form-urlencoded'
const data = require('form-data')
data.append('id', 1)
data.append('num', 12)
axios.post('/postxxxx', data)