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会经常无故丢失,上网查查,也没找到原因. ...
随机推荐
- Qt5使用QFtp,二次封装
1.需要的东西 ftp.cpp,ftp.h是二次封装的ftp类,放在工程下包含 QFtp和qftp.h放在D:\Qt5.7.1\5.7\msvc2013\include\QtNetwork: Qt5F ...
- myeclise中创建maven web程序
myeclipse自带了许多插件,因此使用频率很高,但是对maven框架下web程序似乎不是很好的支持,每次创建web程序总是会报一大堆的异常,因此特此记录一下如何在myeclipse下创建一个web ...
- 【重新分配分片】Elasticsearch通过reroute api重新分配分片
elasticsearch可以通过reroute api来手动进行索引分片的分配. 不过要想完全手动,必须先把cluster.routing.allocation.disable_allocation ...
- P2163 [SHOI2007]园丁的烦恼(cdq分治)
思路 其实是cdq的板子 题目要求询问对于每个给出的xi,yi,xj,yj形如xi<=x<=xj.yi<=y<=yj的x,y对数有多少组 改成四个询问,拆成四个前缀和的形式后就 ...
- (zhuan) Where can I start with Deep Learning?
Where can I start with Deep Learning? By Rotek Song, Deep Reinforcement Learning/Robotics/Computer V ...
- (转载)Unity里实现更换游戏对象材质球
在unity中本来想实现在一个背景墙上更换图片的功能 在网上查了一些资料说是用Image,但我是新手小白刚接触Unity不久好多组建还不会用,就想能不能通过改变游戏对象的材质球来更换游戏对象的背景. ...
- GET和POST中文乱码的解决方法
如果表单中含有中文,采用GET或者POST提交请求时,getParameter()方法接收到的参数值乱码. 1.乱码产生的原因 请求参数通过浏览器发送给Tomcat服务器,浏览器发送编码,但是tomc ...
- 51nod P1305 Pairwise Sum and Divide ——思路题
久しぶり! 发现的一道有意思的题,想了半天都没有找到规律,结果竟然是思路题..(在大佬题解的帮助下) 原题戳>>https://www.51nod.com/onlineJudge/ques ...
- 【Selenium2】【Python多线程】
# all_tests_pro.py import unittest,time,os,multiprocessingimport HTMLTestRunner #查找多有含有thread的文件,文件夹 ...
- 使用JS与CSS3的翻转实现3D翻牌效果
之前我们有讨论过使用CSS3如何实现网页水平翻转的效果,而这次我们介绍的是翻转效果更深一层的应用——3D翻牌效果. 这里我们需要使用flip中轴翻转实现,又因为是3D效果,如果希望呈现一定的3D视角, ...