Axios
基于promise用于浏览器和node.js的http客户端 其特点为:
- 支持浏览器和node.js
- 支持promise
- 能拦截请求和响应
- 能转换请求和响应数据
- 能取消请求
- 自动转换JSON数据
- 浏览器端支持防止CSRF(跨站请求伪造)
安装
- 使用npm
$ npm install axios
- 使用bower
$ bower install axios
- 使用cdn
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
基本使用说明
- 执行 GET 请求
axios.get('/user', {
params: {
ID: 12345
}
}).then(function (response) {
console.log(response);
}).catch(function (error) {
console.log(error);
})
- 执行 POST 请求
axios.post('/user', {
firstName: 'Fred',
lastName: 'Flintstone'
}).then(function (response) {
console.log(response);
}).catch(function (error) {
console.log(error);
})
- 执行多个并发请求
function getUserAccount() {
return axios.get('/user/12345');
}
function getUserPermissions() {
return axios.get('/user/12345/permissions');
}
axios.all([getUserAccount(), getUserPermissions()])
.then(axios.spread(function (acct, perms) {
// 两个请求现在都执行完成
}));
通过向 axios 传递相关配置来创建请求
- axios(config)
// 发送 POST 请求
axios({
method: 'post',
url: '/user/12345',
data: {
firstName: 'Fred',
lastName: 'Flintstone'
}
})
- axios(url[, config])
// 发送 GET 请求(默认的方法)
axios('/user/12345');
- 方法别名
// 在使用别名方法时, url、method、data 这些属性都不必在配置中指定。
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]])
// 处理并发请求的助手函数
axios.all(iterable)
axios.spread(callback)
实例创建
- axios.create([config])
const instance = axios.create({
baseURL: 'https://some-domain.com/api/',
timeout: 1000,
headers: {'X-Custom-Header': 'foobar'}
})
// 可用的实例方法
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 必须的,用于请求的服务器URL
url: '/user',
// 创建请求时使用的方法,如果没有指定,将默认使用get
method: 'post',
// baseURL将自动加载url前,除非‘url’是一个绝对url
// 可以通过设置一个‘baseURL’便于为axios实例的方法传递相对url
baseURL: 'https://baseurl.com/api/',
// transformRequest允许在向服务器发送前,修改请求数据,只能用‘PUT’,‘POST’和
// ‘PATCH’这几个请求方法。后面数组中的函数必须返回一个字符串或ArrayBuffer或Steam
transformRequest: [function (data, headers) {
// 对data进行任意转换处理
return data
}],
// transformResponse在传递给then/catch前,允许修改响应数据
transformResponse: [function (data) {
// 对data进行任意转换处理
return data
}],
// 即将被发送的自定义请求头
headers: {'X-Requested-With': 'XMLHttpRequest'},
// 即将与请求一起发送的URL参数,必须是一个无格式对象或URLSearchParams对象
params: {
ID: 12345
},
// 负责 `params` 序列化的函数
paramsSerializer: function(params) {
return Qs.stringify(params, {arrayFormat: 'brackets'})
},
// 作为请求主体被发送的数据,只适用于 'PUT', 'POST', 和 'PATCH'
// 在没有设置 `transformRequest` 时,必须是以下类型之一:
// - string, plain object, ArrayBuffer, ArrayBufferView, URLSearchParams
// - 浏览器专属:FormData, File, Blob
// - Node 专属: Stream
data: {
firstName: 'Fred'
},
// 指定请求超时的毫秒数(0 表示无超时时间), 如果请求话费了超过 `timeout` 的时间,请求将被中断
timeout: 1000,
// 跨域请求时是否需要使用凭证,默认为false
withCredentials: false,
// `adapter` 允许自定义处理请求,以使测试更轻松,返回一个 promise 并应用一个有效的响应 (查阅 [response docs](#response-api)).
adapter: function (config) {
/* ... */
},
// `auth` 表示应该使用 HTTP 基础验证,并提供凭据
// 将设置一个 `Authorization` 头,覆写掉现有的任意使用 `headers` 设置的自定义 `Authorization`头
auth: {
username: 'axios',
password: 'a1234t'
},
// 服务器响应的数据类型,可以是 'arraybuffer', 'blob', 'document', 'json', 'text', 'stream'
responseType: 'json', // default
responseEncoding: 'utf8', // default
// `xsrfCookieName` 是用作 xsrf token 的值的cookie的名称
xsrfCookieName: 'XSRF-TOKEN', // default
// 带有xsrf的http头部的token值
xsrfHeaderName: 'X-XSRF-TOKEN', // default
// 为上传处理进度事件
onUploadProgress: function (progressEvent) {
// Do whatever you want with the native progress event
},
// 为下载处理进度事件
onDownloadProgress: function (progressEvent) {
// 对原生进度事件的处理
},
// 允许的响应内容的最大尺寸
maxContentLength: 2000,
// 定义对于给定的HTTP 响应状态码是 resolve 或 reject promise 。如果 `validateStatus` 返回 `true` (或者设置为 `null` 或 `undefined`),promise 将被 resolve; 否则,promise 将被 rejecte
validateStatus: function (status) {
return status >= 200 && status < 300; // default
},
// 在 node.js 中 follow 的最大重定向数目,如果设置为0,将不会 follow 任何重定向
maxRedirects: 5, // default
// `socketPath` 定义了在node.js中使用的一个UNIX Socket. socketPath和proxy只能同时定义一个,同时定义时,优先使用socketPath
socketPath: null, // default
// `httpAgent` 和 `httpsAgent` 分别在 node.js 中用于定义在执行 http 和 https 时使用的自定义代理。
httpAgent: new http.Agent({ keepAlive: true }),
httpsAgent: new https.Agent({ keepAlive: true }),
// 'proxy' 定义代理服务器的主机名称和端口
// `auth` 表示 HTTP 基础验证应当用于连接代理,并提供凭据
proxy: {
host: '127.0.0.1',
port: 8080,
auth: {
username: 'niffler'
password: '1234l'
}
},
// 指定用于取消请求的 cancel token
cancelToken: new CancelToken(function (cancel) { })
}
响应结构
{
// 由服务器提供的响应
data: { },
// 来自服务器响应的 HTTP 状态码
status: 200,
// 来自服务器响应的 HTTP 状态信息
statusText: 'OK',
// 服务器响应的头
headers: { },
// 为请求提供的配置信息
config: { },
request: { }
}
接收样例:
axios.get('/Niffler/12345')
.then(function(response) {
console.log(response.data);
console.log(response.status);
console.log(response.statusText);
console.log(response.headers);
console.log(response.config);
})
配置默认值
- 全局的 axios 默认值
axios.defaults.baseURL = 'https://api.example.com';
axios.defaults.headers.common['Authorization'] = AUTH_TOKEN;
- 自定义实例默认值
const instance = axios.create({
baseURL: 'https://api.example.com'
});
instance.defaults.headers.common['Authorization'] = AUTH_TOKEN;
Vue-axios基本用法
安装
$ npm install --save axios vue-axios
在main.js页面引用:
import Vue from 'vue'
import axios from 'axios'
import VueAxios from 'vue-axios'
Vue.use(VueAxios, axios)
使用:
Vue.axios.get(api).then((response) => {
console.log(response.data)
})
this.axios.get(api).then((response) => {
console.log(response.data)
})
this.$http.get(api).then((response) => {
console.log(response.data)
})
带cookie请求问题
axios默认是请求的时候不会带上cookie的,需要通过设置withCredentials: true来解决。
vue-axios-plugin
导入
- 使用Script
<!-- 在 vue.js 之后引入 -->
<script src="https://unpkg.com/vue"></script>
<script src="https://unpkg.com/vue-axios-plugin"></script>
- npm 模块引入
npm install --save vue-axios-plugin
然后在入口文件配置如下:
import Vue from 'Vue'
import VueAxiosPlugin from 'vue-axios-plugin'
Vue.use(VueAxiosPlugin, {
// 请求拦截处理
reqHandleFunc: config => config,
reqErrorFunc: error => Promise.reject(error),
// 响应拦截处理
resHandleFunc: response => response,
resErrorFunc: error => Promise.reject(error)
})
在 Vue 组件上添加了 $http 属性, 它默认提供 get 和 post 方法
this.$http.get(url, data, options).then((response) => {
console.log(response)
})
this.$http.post(url, data, options).then((response) => {
console.log(response)
})
也可以通过 this.$axios 来使用 axios 所有的 api 方法
this.$axios.get(url, data, options).then((response) => {
console.log(response)
})
this.$axios.post(url, data, options).then((response) => {
console.log(response)
})
拦截器
可以截取请求或响应在被 then 或者 catch 处理之前
//添加请求拦截器
axios.interceptors.request.use(config => {
//在发送请求之前做某事,比如说 设置loading动画显示
return config
}, error => {
//请求错误时做些事
return Promise.reject(error)
})
//添加响应拦截器
axios.interceptors.response.use(response => {
//对响应数据做些事,比如说把loading动画关掉
return response
}, error => {
//请求错误时做些事
return Promise.reject(error)
})
//如果不想要这个拦截器也简单,可以删除拦截器
var myInterceptor = axios.interceptors.request.use(function () {/*...*/})
axios.interceptors.request.eject(myInterceptor)