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的更多相关文章

  1. 使用Typescript重构axios(十五)——默认配置

    0. 系列文章 1.使用Typescript重构axios(一)--写在最前面 2.使用Typescript重构axios(二)--项目起手,跑通流程 3.使用Typescript重构axios(三) ...

  2. Web API 源码剖析之默认配置(HttpConfiguration)

    Web API 源码剖析之默认配置(HttpConfiguration) 我们在上一节讲述了全局配置和初始化.本节我们将就全局配置的Configuration只读属性进行展开,她是一个类型为HttpC ...

  3. Axios的详细配置和相关使用

    Axios 是一个基于 promise 的 HTTP 库,可以用在浏览器和 node.js 中. Features 从浏览器中创建 XMLHttpRequests 从 node.js 创建 http  ...

  4. axios统一拦截配置

    在vue项目中,和后台进行数据交互使用axios.要想统一处理所有的http请求和响应,就需要使用axios的拦截器.通过配置http response inteceptor 统一拦截后台的接口数据, ...

  5. vue项目对axios的全局配置

    标准的vue-cli项目结构(httpConfig文件夹自己建的): api.js: //const apiUrl = 'http://test';//测试域名,自己改成自己的 const apiUr ...

  6. Vue基于vuex、axios拦截器实现loading效果及axios的安装配置

    准备 利用vue-cli脚手架创建项目 进入项目安装vuex.axios(npm install vuex,npm install axios) axios配置 项目中安装axios模块(npm in ...

  7. Vue学习使用系列九【axiox全局默认配置以及结合Asp.NetCore3.1 WebApi 生成显示Base64的图形验证码】

    1:前端code 1 <!DOCTYPE html> 2 <html lang="en"> 3 4 <head> 5 <meta char ...

  8. solrcloud线上创建collection,修改默认配置

    一.先看API,创建collection 1.上传配置文件到zookeeper 1) 本地内嵌zookeeper集群:java -classpath ./solr-webapp/webapp/WEB- ...

  9. Asp.net默认配置下,Session莫名丢失的原因及解决

    Asp.net默认配置下,Session莫名丢失的原因及解决 我们平时写的asp.net程序,里面要用到Session来保存一些跨页面的数据.但是Session会经常无故丢失,上网查查,也没找到原因. ...

随机推荐

  1. git如何将一个分支合并到另一个分支?

    答: git merge --no-edit <another branch>

  2. Netty实践与NIO原理

    一.阻塞IO与非阻塞IO Linux网络IO模型(5种) (1)阻塞IO模型 所有文件操作都是阻塞的,以套接字接口为例,在进程空间中调用recvfrom,系统调用直到数据包到达且被复制到应用进程缓冲区 ...

  3. P3232 [HNOI2013]游走

    吐槽 傻了傻了,对着题解改了好长时间最后发现是自己忘了调用高斯消元了... 思路 期望题,分配编号,显然编号大的分给贡献次数小的,所以需要知道每个边被经过次数的期望 然后边被经过的次数的期望就是连接的 ...

  4. 18 Issues in Current Deep Reinforcement Learning from ZhiHu

    深度强化学习的18个关键问题 from: https://zhuanlan.zhihu.com/p/32153603 85 人赞了该文章 深度强化学习的问题在哪里?未来怎么走?哪些方面可以突破? 这两 ...

  5. SalGAN: Visual saliency prediction with generative adversarial networks

    SalGAN: Visual saliency prediction with generative adversarial networks 2017-03-17 摘要:本文引入了对抗网络的对抗训练 ...

  6. watch监控,对比新值和旧值做出相应判断

    数据变化的监控经常使用,我们可以先来看一个简单的数据变化监控的例子.例如天气预报的穿衣指数,它主要是根据温度来进行提示的,当然还有其它的,咱们就不考虑了. html <div id=" ...

  7. Dockerize a .NET Core application

    Dockerize a .NET Core application Introduction This example demonstrates how to dockerize an ASP.NET ...

  8. CSS3实现基本图形

    http://blog.csdn.net/laokdidiao/article/details/51189476 代码: <!DOCTYPE html> <html> < ...

  9. python爬虫训练——爬poj题目

    首先要解决的就是不同的题目在不同的页上,也就是要实现翻页功能,自动获取所要爬取的地址,通过分析可以得出不同的页面也就是volume=后面的数字不同 所以我们可以用re模块来替换即可: new_url ...

  10. 每天一个小程序—0013题(爬图片+正则表达式 or BeautifulSoup)

    第 0013 题: 用 Python 写一个爬图片的程序,爬 这个链接里的日本妹子图片 :-) 关于python3的urllib模块,可以看这篇博客:传送门 首先是用urlopen打开网站并且获取网页 ...