axios 是一个基于Promise 用于浏览器和 nodejs 的 HTTP客户端,目前主流的Vue项目中,多采用axios来发送ajax请求,因此学习一下axios
一、简单使用
这里以vue-cli构造的项目下使用axios为例
1.安装引入
在项目目录下使用命令行npm install axios --save
需要注意的是,一般我们在安装插件的时候可以通过在main.js中使用Vue.use(...)
来注册,但是axios
并不能直接使用Vue.use()
来注册,因此要在需要使用axios
的组件中通过import axios from 'axios'
即时引入,之后直接使用axios
实例即可
<template>……</template>
<script>
……
import axios from 'axios'
export default {
……
methods: {
getData () {
axios.get('/api/index.json').then(this.getDataSucc)
},
getDataSucc (response) {
……
}
}
}
</script>
<style></style>
为了避免在多个组件文件都导入axios
,可以在main.js文件中对Vue的原型链进行操作
import axios from 'axios'
Vue.prototype.$axiot = axios
这样在其他单文件组件中直接通过this.$axios
就能调用axios
了
2.Get、Post请求
(1).axios.get(path)
该方法可以直接将url作为参数,会返回一个Promise
对象,通过Promise
对象的then(func)
方法可以传入回调函数,该函数会接收一个响应对象
axios.get('/user?ID=12345')
.then(function (response) {
console.log(response);
})
如果请求异常,可以通过Promise
对象的catch(func)
来处理异常情况
axios.get('/user?ID=12345')
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
也可以通过params
对象传递参数
axios.get('/user', {
params: {
ID: 12345
}
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
(2).axios.post(path,{...})
axios.post('/user', {
firstName: 'Fred',
lastName: 'Flintstone'
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
3、并发请求
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) {
// Both requests are now complete
}));
二、axios API
使用axios
时,可以通过将相关配置传递给axios
来进行请求。
1.post请求
使用axios(config)
axios({
method: 'post',
url: '/user/12345',
data: {
firstName: 'Fred',
lastName: 'Flintstone'
}
});
2.get请求
使用axios(url[, config])
,从这个接口可以看出,axios
默认情况下是使用get请求的
3.方法别名
axios
提供了对应请求方法的别名,按需求使用即可,需要注意的是当使用别名方法时,不需要在config
中指定url
、method
和data
属性。
axios.request(config)
axios.get(url [,config])
axios.delete(url [,config])
axios.head(url [,config])
axios.post(url [,data [,config]])
axios.put(url [,data [,config]])
axios.patch(url [,data [,config]])
4.请求配置详解
这些是用于发出请求的可用配置选项。只有url是必需的。如果未指定方法,请求将默认为GET。
{
url: '/user',
method: 'get',
// `data`是要作为请求主体发送的数据
// 仅适用于请求方法“PUT”,“POST”和“PATCH”
// 当没有设置`transformRequest`时,必须是以下类型之一:
// - string, plain object, ArrayBuffer, ArrayBufferView, URLSearchParams
// - Browser only: FormData, File, Blob
// - Node only: Stream
data: {
firstName: 'Fred'
},
// “responseType”表示服务器将响应的数据类型
// 包括 'arraybuffer', 'blob', 'document', 'json', 'text', 'stream'
responseType: 'json', // default
// `baseURL`将被添加到`url`前面,除非`url`是绝对的。
baseURL: 'https://some-domain.com/api/',
// `transformRequest`允许在请求数据发送到服务器之前对其进行更改
// 这只适用于请求方法'PUT','POST'和'PATCH'
// 数组中的最后一个函数必须返回一个字符串,一个 ArrayBuffer或一个 Stream
transformRequest: [function (data) {
....Do whatever you want to transform the data....
return data;
}],
// `transformResponse`允许在 then / catch之前对响应数据进行更改
transformResponse: [function (data) {
....Do whatever you want to transform the data....
return data;
}],
// `headers`是要发送的自定义 headers
headers: {'X-Requested-With': 'XMLHttpRequest'},
// `params`是要与请求一起发送的URL参数
// 必须是纯对象或URLSearchParams对象
params: {
ID: 12345
},
// `paramsSerializer`是一个可选的函数,负责序列化`params`
// (e.g. https://www.npmjs.com/package/qs, http://api.jquery.com/jquery.param/)
paramsSerializer: function(params) {
return Qs.stringify(params, {arrayFormat: 'brackets'})
},
// `timeout`指定请求超时之前的毫秒数。
// 如果请求的时间超过'timeout',请求将被中止。
timeout: 1000,
// `withCredentials`指示是否跨站点访问控制请求
// should be made using credentials
withCredentials: false, // default
// `adapter'允许自定义处理请求,这使得测试更容易。
// 返回一个promise并提供一个有效的响应(参见[response docs](#response-api))
adapter: function (config) {
/* ... */
},
// `auth'表示应该使用 HTTP 基本认证,并提供凭据。
// 这将设置一个`Authorization'头,覆盖任何现有的`Authorization'自定义头,使用`headers`设置。
auth: {
username: 'janedoe',
password: 's00pers3cret'
},
//`xsrfCookieName`是要用作 xsrf 令牌的值的cookie的名称
xsrfCookieName: 'XSRF-TOKEN', // default
// `xsrfHeaderName`是携带xsrf令牌值的http头的名称
xsrfHeaderName: 'X-XSRF-TOKEN', // default
// `onUploadProgress`允许处理上传的进度事件
onUploadProgress: function (progressEvent) {
// 使用本地 progress 事件做任何你想要做的
},
// `onDownloadProgress`允许处理下载的进度事件
onDownloadProgress: function (progressEvent) {
// Do whatever you want with the native progress event
},
// `maxContentLength`定义允许的http响应内容的最大大小
maxContentLength: 2000,
// `validateStatus`定义是否解析或拒绝给定的promise
// HTTP响应状态码。如果`validateStatus`返回`true`(或被设置为`null`promise将被解析否则,promise将被拒绝。
validateStatus: function (status) {
return status >= 200 && status < 300; // default
},
// `maxRedirects`定义在node.js中要遵循的重定向的最大数量。如果设置为0,则不会遵循重定向。
maxRedirects: 5, // 默认
// `httpAgent`和`httpsAgent`用于定义在node.js中分别执行http和https请求时使用的自定义代理。
// 允许配置类似`keepAlive`的选项,默认情况下不启用。
httpAgent: new http.Agent({ keepAlive: true }),
httpsAgent: new https.Agent({ keepAlive: true }),
// 'proxy'定义代理服务器的主机名和端口
// `auth`表示HTTP Basic auth应该用于连接到代理,并提供credentials。
// 这将设置一个`Proxy-Authorization` header,覆盖任何使用`headers`设置的现有的`Proxy-Authorization` 自定义 headers。
proxy: {
host: '127.0.0.1',
port: 9000,
auth: : {
username: 'mikeymike',
password: 'rapunz3l'
}
},
// “cancelToken”指定可用于取消请求的取消令牌
// (see Cancellation section below for details)
cancelToken: new CancelToken(function (cancel) {
})
}
5.配置默认值
axios
可以提前配置默认值,方式如下
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';
6.拦截器
你可以在请求或响应在被then
或者catch
处理之前截取
//添加请求拦截器
axios.interceptors.request.use(function(config){
//在发送请求之前做某事
return config;
},function(error){
//请求错误时做些事
return Promise.reject(error);
});
//添加响应拦截器
axios.interceptors.response.use(function(response){
//对响应数据做些事
return response;
},function(error){
//请求错误时做些事
return Promise.reject(error);
});
7.错误处理
axios.get('/ user / 12345')
.catch(function(error){
if(error.response){
//请求已发出,但服务器使用状态代码进行响应
//落在2xx的范围之外
console.log(error.response.data);
console.log(error.response.status);
console.log(error.response.headers);
} else {
//在设置触发错误的请求时发生了错误
console.log('Error',error.message);
}}
console.log(error.config);
});
8.状态码错误范围
您可以使用validateStatus
配置选项定义自定义HTTP状态码错误范围。
axios.get('/ user / 12345',{
validateStatus:function(status){
//仅当状态代码大于或等于500时拒绝
return status < 500;
}}
})
三、数据发送格式
默认情况下,axios
将JavaScript对象序列化为JSON。要以应用程序/x-www-form-urlencoded
格式发送数据,可以使用URLSearchParams API
var params = new URLSearchParams();
params.append('param1', 'value1');
params.append('param2', 'value2');
axios.post('/foo', params);