Axios的默认配置(碎片知识)API
axios API
axios(config)
axios({
method: 'Post',
url: '/user/123',
data: {
//略
}
})
axios(url[, config])
//默认发送一个GET request
axios('/user/123');
Request method aliases
别名,提供所有请求方法
axios.delete(url[, config])
axios.head(url[, config])
axios.post(url[, data[, config]])
例子:
axios.get('/user?id=123')
.then(response => {
//handle success
})
.catch(err => {
//handle error
})
.then(() =>{
// always executed
});
还可以:axios.get(url, config)
axios.get('/user', {
paramis: {
id: 123,
}
})
.then().catch().then();
甚至可以用ES2017:
async function getUser() {
try{
onst response = await axios.get('/user?id=123');
console.log(response)
} catch (error) {
console.error(error)
}
}
并发Concurrency
帮助函数处理并发请求。
axios.all(iterable)
axios.spread(callback)
function getUserAccount() {
return axios.get('/user/123')
}
function getUserPermissions() {
return axios.get('/user/123/permisssions')
}
axios.all([getUserAccount(), getUserPermissions()])
.then(axios.spread(function(acct, perms) {
//2个请求都完成后,执行这里的代码
}))
创建一个实例用于客制化config
const instance = axios.create({
baseURL: 'https://some-domain.com/api/',
timeout: 1000,
headers: {'X-Custom-Header': 'foobar'}
})
实例方法:
request, get, head,options, post, put, patch, getUri([config])
Request Config
常用配置:(全面的配置见git)
{
url: ''/user',
methods: 'get',
//baseURL会放到url前面,除非url是全的url。
//对axios的实例传递相对URl,使用baseURL会更方便。
baseURL: 'https://some-domain.com/api/',
//在请求数据被发送到服务器前改变要发送的data
//只能用于put, post, pathc请求方法
//在数组中的最后一个函数必须返回一个string, 或者一个实例(FormData, Stream, Buffer, ArrayBuffer)
//也可以修改header对象。
transformRequest: [function(data, headers) {
//写要改变数据的代码
return data
}]
//当响应数据返回后,在它传入then/catch之前修改它
transformResponse: [function(data) { //...; return data; }]
//客制
header: {...},
params: {
id: 123;
},
//要发送的请求body, 只用在put ,post, patch.
data: { //...}
//如果请求时间超过timeout,则终止这个请求。
timeout: 1000,
}
ResponseConfig
{
data: {},
status: 200,
statusText: 'ok',
//服务器响应的headers
headers: {},
//由axios提供的配置,用于request
config: {},
//
request: {},
}
Config Defaults
指定默认的配置,用于每个请求。
全局
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;
Config order of precedence
实例的默认配置,可以修改。
//此时默认timeout是0
const instance = axions.create()
//改变设置实例的的配置。
instance.defaults.timeout = 2500;
当使用这个实例发送请求时,还可以改变实例的默认配置。
instance.get('/longRequest', {
timeout: 5000
})
Interceptors
在它们被then.catch处理之前,拦截请求或者响应.
axios.interceptors.request.use(
function(config) {
//在请求发送前,执行这里的代码
return config;
},
function(error) {
//do sth with request error
return Promise.reject(error);
}
); axios.interceptors.response.use(
function(response) {
//在接收响应数据前,执行这里的代码
return response;
},
function(error) {
//do sth with response error
return Promise.reject(error)
}
);
真实例子:
<script>
export default {
//...略data函数和methods对象
created() {
// 增加一个响应拦截。
// 这个拦截,不处理function(response),所以用undefined
// 只对返回错误状态码401,作出设置。
this.$http.interceptors.response.use(undefined, function(err){
return new Promise(function(resolve, reject) {
if (err.status === 401 && err.config && !err.config.__isRetryRequest) {
this.$store.dispatch(logout)
}
throw err;
})
})
}
如果之后需要移除interceptor使用eject().
interceptor也可以用于custom instance of axios.
Cancellation
可以使用a cancel token来取消一个请求。(具体见git)
Using application/x-www-form-urlencoded format
默认,axios serializes JavaScript对象成JSON格式。
并使用application/x-www-form-urlencoded format 。
你也可以使用其他方式:
Browser
Node.js
TypeScript。
Axios的默认配置(碎片知识)API的更多相关文章
- 使用Typescript重构axios(十五)——默认配置
0. 系列文章 1.使用Typescript重构axios(一)--写在最前面 2.使用Typescript重构axios(二)--项目起手,跑通流程 3.使用Typescript重构axios(三) ...
- Web API 源码剖析之默认配置(HttpConfiguration)
Web API 源码剖析之默认配置(HttpConfiguration) 我们在上一节讲述了全局配置和初始化.本节我们将就全局配置的Configuration只读属性进行展开,她是一个类型为HttpC ...
- Axios的详细配置和相关使用
Axios 是一个基于 promise 的 HTTP 库,可以用在浏览器和 node.js 中. Features 从浏览器中创建 XMLHttpRequests 从 node.js 创建 http ...
- axios统一拦截配置
在vue项目中,和后台进行数据交互使用axios.要想统一处理所有的http请求和响应,就需要使用axios的拦截器.通过配置http response inteceptor 统一拦截后台的接口数据, ...
- vue项目对axios的全局配置
标准的vue-cli项目结构(httpConfig文件夹自己建的): api.js: //const apiUrl = 'http://test';//测试域名,自己改成自己的 const apiUr ...
- Vue基于vuex、axios拦截器实现loading效果及axios的安装配置
准备 利用vue-cli脚手架创建项目 进入项目安装vuex.axios(npm install vuex,npm install axios) axios配置 项目中安装axios模块(npm in ...
- Vue学习使用系列九【axiox全局默认配置以及结合Asp.NetCore3.1 WebApi 生成显示Base64的图形验证码】
1:前端code 1 <!DOCTYPE html> 2 <html lang="en"> 3 4 <head> 5 <meta char ...
- solrcloud线上创建collection,修改默认配置
一.先看API,创建collection 1.上传配置文件到zookeeper 1) 本地内嵌zookeeper集群:java -classpath ./solr-webapp/webapp/WEB- ...
- Asp.net默认配置下,Session莫名丢失的原因及解决
Asp.net默认配置下,Session莫名丢失的原因及解决 我们平时写的asp.net程序,里面要用到Session来保存一些跨页面的数据.但是Session会经常无故丢失,上网查查,也没找到原因. ...
随机推荐
- 利用Selenium自动化测试android wap页
http://blogs.360.cn/360qtest/2014/04/01/%E5%88%A9%E7%94%A8selenium%E8%87%AA%E5%8A%A8%E5%8C%96%E6%B5% ...
- if语句学习
#print("您好,我叫周星驰") ''' x=1+2+3 print(x*4) print(x**x) a=input("请输入相应的数字a") a=int ...
- MSYS2 更换国内源
转自 : http://www.cnblogs.com/findumars/p/6546088.html 最近一段时间不知怎么的,使用默认的 MSYS2 源升级软件或是安装新软件的特别的慢.所以就翻了 ...
- [NOI1995]石子合并 四边形不等式优化
链接 https://www.luogu.org/problemnew/show/P1880 思路 总之就是很牛逼的四边形不等式优化 复杂度\(O(n^2)\) 代码 #include <ios ...
- (转)JPA & Restful
参考博客: JPA: https://www.jianshu.com/p/b6932740f3c0 https://shimo.im/docs/zOer2qMVEggbF33d/ Restful: h ...
- Windows环境下32位汇编语言程序设计笔记-基础篇
内存模式 .386 .model flat,stdcall ;子程序调用模式,win32中只能用stdcall,因为win32api调用使用的这个 option casemap:none ;定义了程序 ...
- 【转载】C++宏定义详解
摘自:http://blog.chinaunix.net/uid-21372424-id-119797.html C++宏定义详解 2011-02-14 23:33:24 分类: C/C++ ...
- 转一篇 ShaderVariantCollection介绍的比较详细的文章 感谢作者
http://www.seven-fire.cn/archives/174 Unity3D Shader加载时机和预编译 焱燚(七火) | 2016年7月6日 | UnityShader ...
- WebSocket 教程
转载自:http://www.ruanyifeng.com/blog/2017/05/websocket.html WebSocket 是一种网络通信协议,很多高级功能都需要它. 本文介绍 WebSo ...
- java用毫秒数做日期计算的一个踩坑记录
错误示例: Date today = new Date(); Date nextMonth = new Date(today.getTime() + 30* 1000*60*60*24); print ...