npm下载
npm install axios
带query参数形式的get请求
axios.get('/user?ID=12345')
.then( function (response){
// 返回的数据
console.log(response);
})
.catch(function (error) {
// 错误信息
console.log(error)
})
.finally(function (){
// 进行最终处理
});
使用params参数形式的get请求
axios.get('/user', {
params: {
ID: 123
}
})
.then( function (response){
console.log(response);
})
.catch( function (error) {
console.log(error);
})
.finally( function (){
// 最终处理
})
使用async/await方式发起get请求
async function getUser(){
try {
const response = await axios.get('user?ID=123');
console.log(response)
} catch (error) {
console.log(error)
}
}
发起post请求
axios.post('/user', {
firstName: 'Fred',
lastName: 'Find'
})
.then( function (response){
console.log(response);
})
.catch( function (error) {
console.log(error);
})
get与post用法细微差距
请求方式不一样
这两个是不同的请求方式,get请求方式携带的数据信息是放置请求信息的header,可以通过url显性展示出来,而post请求方式携带的数据信息是放置在请求信息的body。
参数方式不一样
axios发起Get请求,第二个参数是 { },里面是一个parms对象
axios.get('/user', {
params: {
ID: 12345
}
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
})
.then(function () {
// always executed
});
axios发起Post请求,第二个参数是一个对象
axios.post('/user', {
firstName: 'Fred',
lastName: 'Flintstone'
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
同时发起多个请求
function getUser() {
return axios.get('/user/1234');
}
function getUserPermissions() {
return axios.get('/user/1234/permissions');
}
axios.all([getUser(),getUserPermissions()])
.then( axios.spread( function (userResp, permResp){
// 只有上面的请求全部成功后才能执行此回调函数
console.log('UserInfo',userResp);
console.log('permissionInfo',permResp);
}))
.catch (function (error) {
// 只要有一个请求失败,都会失败
console.log(error);
});
以配置的形式发起请求
axios({
method: 'post',
url: '/user/1234',
data: {
firstName: 'Fred',
lastName: 'Find'
}
}).then( function (response) {
console.log(response);
})
设置返回数据的类型
axios({
method: 'get',
url: 'http://bit.ly/2mTM3nY',
responseType: 'stream'
})
.then( function (response) {
// 此处使用node.js语法
// 将返回的数据结果通过管道,传输给fs模块创建文件
response.data.pipe(fs.createWriteStream('a.jpg'));
});
axios默认get请求
axios实例
const instance = axios.create({
// 默认请求的路径
baseUrl: 'http://some-domain.com/api/',
// 超时时间
timeout: 1000,
// 自定义请求头部信息
headers: {
'X-Custom-Header': 'foobar'
}
}
request API 解读
{
// 请求的url
url: '/user',
// 请求的方法,默认是get方式
method: 'get',
// url前缀,拼接到url前面
// http://baidu.com/user
baseUrl: 'http://baidu.com/',
// 请求参数的预处理,在发送请求到服务器之前,将数据进行预处理
// 此方法仅仅可用于PUT、POST、PATCH和DELETE方法
// 预处理的返回数据类型必须是string或者Buffer、ArrayBuffer
// 还可以定义请求头
transformRequest: [function (data, headers) {
// 在这里进行数据处理
return data;
}],
// 返回数据预处理,返回返回数据之前,将数据进行预处理
transformResponse: [ function (data) {
return data;
}],
// 构造自定义请求头部
headers: {'X-Requested-With': 'XMLHttpRequest'},
// URL参数
params: {
ID: 1234
},
// 将请求的参数序列化
paramsSerializer: function (params) {
return Qs.stringify(params, {arrayFormat: 'brackets'})
},
// 请求数据(request body)
data: {
firstName: 'Fred'
},
// 设置请求超时时间,如果请求时间大于超时时间,此请求会被中断
timeout: 1000 // 默认值为0,永不超时
// 表示跨域请求时是否需要使用凭证,默认为false
// 设置为true,发送请求时会带上cookie
withCredentials: false,
// 自定义处理请求
adapter: function ( config) {
}
// HTTP基础验证,并提供凭证
auth: {
username: 'janedoe',
password: 's00pers3cret'
},
// 数据返回类型
// 参数有arraybuffer、document、json、text、stream,默认为json
responseType: 'json'
// 返回的编码类型
responseEncoding: 'utf8',
// xsrf cookie用于xsrf tooken
xsrfCookieName: 'XSRF-TOKEN', // default
// xsrf name 用于xsrf tooken
xsrfHeaderName: 'X-XSRF-TOKEN', // default
// 上传进度处理事件
onUploadProgress: function (progressEvent) {
// Do whatever you want with the native progress event
},
// 下载进度处理事件
onDownloadProgress: function (progressEvent) {
// Do whatever you want with the native progress event
},
// 最大响应内容长度
maxContentLength: 2000,
// 返回响应的Http Code
// 无论返回成功还是失败,都返回Http Code
validateStatus: function (status) {
return status >= 200 && status < 300; // default
},
// 重定向最大次数,设置为0不会进行任何重定向
maxRedirects: 5,
// 用于node.js定义soket
soketPath: null,
// http https 自定义代理配置,默认keepAlive没有启动
httpAgent: new http.Agent({ keepAlive: true }),
httpsAgent: new https.Agent({ keepAlive: true }),
// 设置代理相关
proxy: {
host: '127.0.0.1',
port: 9000,
auth: {
username: 'mikeymike',
password: 'rapunz3l'
}
},
// 用于取消请求
cancelToken: new CancelToken(function (cancel) {
})
}
Reponse相关解读
{
// 服务器返回的数据
data: {},
// 服务器返回的状态码
status: 200,
// 返回状态的信息
statusText: 'OK',
// 返回的头部信息
headers: {},
// 发起请求的配置
config: {},
// `request` is the request that generated this response
// It is the last ClientRequest instance in node.js (in redirects)
// and an XMLHttpRequest instance in the browser
request: {}
}
实例
axios.get('/user/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;
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
axios实例后配置
const instance = axios.create({
baseURL: 'https://api.example.com'
});
instance.defaults.headers.common['Authorization'] = AUTH_TOKEN;
拦截器
在发起请求前或者返回数据之前进行拦截和处理
请求拦截器
axios.interceptors.request.use(function (config) {
// Do something before request is sent
return config;
}, function (error) {
// Do something with request error
return Promise.reject(error);
});
响应拦截器
axios.interceptors.response.use(function (response) {
// Do something with response data
return response;
}, function (error) {
// Do something with response error
return Promise.reject(error);
});
移除拦截器
const myInterceptor = axios.interceptors.request.use(function () {/*...*/});
axios.interceptors.request.eject(myInterceptor)
使用axios实例创建拦截器
const instance = axios.create();
instance.interceptors.request.use(function () {/*...*/});
错误处理
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 if (error.request) {
// 请求以及发出但是没有响应
// `error.request` is an instance of XMLHttpRequest in the browser and an instance of
// http.ClientRequest in node.js
console.log(error.request);
} else {
// 在配置请求前触发了什么错误
console.log('Error', error.message);
}
console.log(error.config);
});
validateStatus 配置返回状态码错误范围
axios.get('/user/12345', {
validateStatus: function (status) {
return status < 500; // Reject only if the status code is greater than or equal to 500
}
})
取消请求
const CancelToken = axios.CancelToken;
const source = CancelToken.source();
axios.get('/user/12345', {
cancelToken: source.token
}).catch(function (thrown) {
if (axios.isCancel(thrown)) {
console.log('Request canceled', thrown.message);
} else {
// handle error
}
});
axios.post('/user/12345', {
name: 'new name'
}, {
cancelToken: source.token
})
// 执行取消请求
source.cancel('Operation canceled by the user.');
通过传入一个executor在CancelToken构造方法的方式取消请求
const CancelToken = axios.CancelToken;
let cancel;
axios.get('/user/12345', {
cancelToken: new CancelToken(function executor(c) {
// An executor function receives a cancel function as a parameter
cancel = c;
})
});
// cancel the request
cancel();
数据参数格式化成application/x-www-form-urlencoded
URLSearchParams
const params = new URLSearchParams();
params.append('param1', 'value1');
params.append('param2', 'value2');
axios.post('/foo', params);
qs
const qs = require('qs');
axios.post('/foo', qs.stringify({ 'bar': 123 }));
ES6
import qs from 'qs';
const data = { 'bar': 123 };
const options = {
method: 'POST',
headers: { 'content-type': 'application/x-www-form-urlencoded' },
data: qs.stringify(data),
url,
};
axios(options);
Node.js
const querystring = require('querystring');
axios.post('http://something.com/', querystring.stringify({ foo: 'bar' }));