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. topcoder srm 390 div1

    problem1 link 记录一个模$k$之后的值是否出现过,出现过则出现循环,无解:否则最多$k$ 次一定能出现0. import java.util.*; import java.math.*; ...

  2. Oracle常用函数——COALESCE

    COALESCE 含义:COALESCE是一个函数, (expression_1, expression_2, ...,expression_n)依次参考各参数表达式,遇到非null值即停止并返回该值 ...

  3. linux内核中的PTP clock是什么?

    答: Precise Time Protocol(PTP),这是一种高精度时间同步协议,PTP是在硬件级实现的,因此需要硬件支持才能实现高精度时间同步

  4. linux内核中的IPIs是什么?

    答: 处理器间中断(Interprocessor Interrupts)

  5. SpringBoot 消息转换器 HttpMessageConverter

    1.简介: Spring在处理请求时,由合适的消息转换器将请求报文绑定为方法中的形参对象,在这里,同一个对象就有可能出现多种不同的消息形式,比如json和xml.同样,当响应请求时,方法的返回值也同样 ...

  6. wqCms6.0在IIS6的Getshell

    2017-02-15发布 一.漏洞利用点 漏洞文件:admin_UploadDataHandler.ashx 自定义构造上传点 二.hack it 三.POC <html> <bod ...

  7. oogle advertiser api开发概述——速率限制

    速率限制 为了向遍布全球的 AdWords API 用户提供可靠的服务,我们使用令牌桶算法来衡量请求数并确定每秒查询数 (QPS) 速率.这样做的目的是阻止恶意的或不可控的软件大量入侵 AdWords ...

  8. python3.6配置libsvm2.2

    参考自:https://blog.csdn.net/weixin_35884839/article/details/79398085 由于需要使用到libsvm,所以开始配这个,所幸一次性就成功了. ...

  9. RN 使用第三方组件之react-native-image-picker(拍照/从相册获取图片)

    首先给个github地址:https://github.com/react-community/react-native-image-picker  英文不行的看下面这个笔记 该插件可以同时给iOS和 ...

  10. UIUseImgWindow

    using System;using UnityEngine;using UnityEngine.UI;using UnityEditor;using System.Collections;using ...