这是我参与更文挑战的第3天,活动详情查看: 更文挑战
Axios 是一个基于 promise 的 HTTP 库,可以用在浏览器和 node.js 中
npm安装
npm install axios
引入
import axios from 'axios'
GET请求示例
axios.get('/test?id=12345')
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
})
POST请求示例
axios.post('/test', {
paramsA: 'a',
paramsB: 'b'
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
})
多个请求
function getA() {
return axios.get('/test/123');
}
function getB() {
return axios.get('/test/456');
}
axios.all([getA(), getB()])
.then(axios.spread(function (acct, perms) {
...
}))
创建axios实例
const service = axios.create({
baseURL: BASE_URL,
timeout: 30000
})
实例的方法
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]])
请求的可配置项
{
url: '/test', // 请求的接口地址
method: 'get', // 请求的方法,默认GET
// 可以用于区分不同环境,当url不是绝对路径,baseURL + url 为接口的请求地址
baseURL: 'https://IP-or-domain.com/api/',
// 在向服务器发送前,修改请求数据
// 只能用在 'PUT', 'POST' 和 'PATCH' 这几个请求方法
// 后面数组中的函数必须返回一个字符串,或 ArrayBuffer,或 Stream
transformRequest: [function (data, headers) {
// 操作data , headers 等
return data;
}],
// 在传递给 then/catch 前,允许修改响应数据
transformResponse: [function (data) {
// 操作data
return data;
}],
// 请求头
headers: {'X-Requested-With': 'XMLHttpRequest'},
// URL 参数
params: {
id: 12345
},
// 参数序列化
paramsSerializer: function(params) {
return Qs.stringify(params, {arrayFormat: 'brackets'})
},
// 作为请求主体被发送的数据
data: {
params: 'test'
},
// 请求超时时间(毫秒)
timeout: 30000,
// 跨域时是否携带cookie信息
withCredentials: false, // 默认false
// 允许自定义处理请求,返回一个 promise 并应用一个有效的响应
adapter: function (config) {
...
},
// 使用 HTTP 基础验证,并提供凭据
// 这将设置一个 `Authorization` 头,覆写掉现有的任意使用 `headers` 设置的自定义 `Authorization`头
auth: {
username: 'janedoe',
password: 's00pers3cret'
},
responseEncoding: 'utf8', // default
// 服务器响应的数据类型,可选项 'arraybuffer', 'blob', 'document', 'json', 'text', 'stream'
responseType: 'json', // 默认值是json
// 用作 xsrf token 的值的cookie的名称
xsrfCookieName: 'XSRF-TOKEN', // default
xsrfHeaderName: 'X-XSRF-TOKEN', // default
// 允许为上传处理进度事件
onUploadProgress: function (progressEvent) {
// Do whatever you want with the native progress event
},
// 允许为下载处理进度事件
onDownloadProgress: function (progressEvent) {
// Do whatever you want with the native progress event
},
// 设置http响应内容的最大长度
maxContentLength: 2000,
// 定义可获得的http响应状态码
// return true、设置为null或者undefined,promise将resolved,否则将rejected
validateStatus: function (status) {
return status >= 200 && status < 300; // default
},
// 定义在 node.js 中 follow 的最大重定向数目
// 如果设置为0,将不会 follow 任何重定向
maxRedirects: 5, // default
// `httpAgent` 和 `httpsAgent` 分别在 node.js 中用于定义在执行 http 和 https 时使用的自定义代理。允许像这样配置选项:
// `keepAlive` 默认没有启用
httpAgent: new http.Agent({ keepAlive: true }),
httpsAgent: new https.Agent({ keepAlive: true }),
// 'proxy' 定义代理服务器的主机名称和端口
// `auth` 表示 HTTP 基础验证应当用于连接代理,并提供凭据
// 这将会设置一个 `Proxy-Authorization` 头,覆写掉已有的通过使用 `header` 设置的自定义 `Proxy-Authorization` 头。
proxy: {
host: '127.0.0.1',
port: 9000,
auth: {
username: 'mikeymike',
password: 'rapunz3l'
}
},
// 指定用于取消请求的 cancel token
cancelToken: new CancelToken(function (cancel) {
})
}
封装公共请求方法
export default async function ({
funName = "",
url = "",
data = {},
method = "GET",
urlParams = "",
options = {}
}) {
const config = { ...options, funName };
config.method = method.toLocaleUpperCase();
config.url = url;
urlParams && (config.url += "/" + urlParams);
config.method == "GET" ? (config.params = data) : (config.data = data);
return await service(config);
}
全局默认配置
axios.defaults.baseURL = 'https://domain.com';
axios.defaults.headers.common['Authorization'] = AUTH_TOKEN;
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';