基于promise
,用于浏览器和node.js
的http客户端
1、 利用 npm 安装 npm install axios --save
2、 利用 bower 安装 bower install axios --save
3、 直接利用 cdn 引入 ``
1、带query参数形式的get请求
axios.get('/users?name=yxh')
.then( function (response){
// 返回的数据
console.log(response);
})
.catch(function (error) {
// 错误信息
console.log(error)
})
.finally(function (){
// 进行最终处理
});
2、使用params参数形式的get请求
axios.get('/users', {
params: {
name: 'yxh'
}
})
.then( function (response){
console.log(response);
})
.catch( function (error) {
console.log(error);
})
.finally( function (){
// 最终处理
})
axios.post('/users', {
name: 'Yang',
age: '18'
})
.then( function (response){
console.log(response);
})
.catch( function (error) {
console.log(error);
})
这两个是不同的请求方式,get请求方式携带的数据信息是放置请求信息的header,可以通过url显性展示出来,而post请求方式携带的数据信息是放置在请求信息的body。
axios发起Get请求,第二个参数是 { },里面是一个parms对象
axios.get('/users', {
params: {
name: 'yxh'
}
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
})
.then(function () {
// always executed
});
axios发起Post请求,第二个参数是一个对象
axios.post('/users', {
name: 'Yang',
age: '18'
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
function getUser() {
return axios.get('/users/yxh');
}
function getUserInfo() {
return axios.get('/users/yxh/info');
}
axios.all([getUser(),getUserInfo()])
.then( axios.spread( function (userRes, infoRes){
// 只有上面的请求全部成功后才能执行此回调函数
console.log('User',userRes);
console.log('UsersInfo',infoRes);
}))
.catch (function (error) {
// 只要有一个请求失败,都会失败
console.log(error);
});
//iterable是一个可以迭代的参数如数组等
axios.all(iterable)
//callback要等到所有请求都完成才会执行
axios.spread(callback)
axios({
method: 'post',
url: '/users/',
data: {
name: 'Yang',
age: '18'
}
}).then( function (response) {
console.log(response);
})
axios({
method: 'get',
url: 'http://qn2.huat.xyz/2.jpg',
responseType: 'stream'
})
.then( function (response) {
// 此处使用node.js语法
// 将返回的数据结果通过管道,传输给fs模块创建文件
response.data.pipe(fs.createWriteStream('2.jpg'));
});
axios默认get请求
const instance = axios.create({
// 默认请求的路径
baseUrl: 'http://localhost:3000/api/',
// 超时时间
timeout: 1000,
// 自定义请求头部信息
headers: {
'X-Custom-Header': 'foobar'
}
}
{
// 请求的url
url: '/users',
// 请求的方法,默认是get方式
method: 'get',
// url前缀,拼接到url前面
// http://localhost:3000/users
baseUrl: 'http://localhost:3000/',
// 请求参数的预处理,在发送请求到服务器之前,将数据进行预处理
// 此方法仅仅可用于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: {
name: 'yxh'
},
// 将请求的参数序列化
paramsSerializer: function (params) {
return Qs.stringify(params, {arrayFormat: 'brackets'})
},
// 请求数据(request body)
data: {
name: 'Yang'
},
// 设置请求超时时间,如果请求时间大于超时时间,此请求会被中断
timeout: 1000 // 默认值为0,永不超时
// 表示跨域请求时是否需要使用凭证,默认为false
// 设置为true,发送请求时会带上cookie
withCredentials: false,
// 自定义处理请求
adapter: function ( config) {
}
// HTTP基础验证,并提供凭证
auth: {
username: 'yxh',
password: '19980912'
},
// 数据返回类型
// 参数有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: 'jarvis',
password: 'jarvis'
}
},
// 用于取消请求
cancelToken: new CancelToken(function (cancel) {
})
}
{
// 服务器返回的数据
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('/users/yxh')
.then(function (response) {
console.log(response.data);
console.log(response.status);
console.log(response.statusText);
console.log(response.headers);
console.log(response.config);
});
axios.defaults.baseURL = 'https://cesi.huat.xyz';
axios.defaults.headers.common['Authorization'] = AUTH_TOKEN;
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
const instance = axios.create({
baseURL: 'https://cesi.huat.xyz'
});
instance.defaults.headers.common['Authorization'] = AUTH_TOKEN;
config配置将会以优先级别来合并,顺序是lib/defauts.js中的默认配置,然后是实例中的默认配置,最后是请求中的config参数的配置,越往后等级越高,后面的会覆盖前面的例子。
//创建一个实例的时候会使用libray目录中的默认配置
//在这里timeout配置的值为0,来自于libray的默认值
var instance = axios.create();
//回覆盖掉library的默认值
//现在所有的请求都要等2.5S之后才会发出
instance.defaults.timeout = 2500;
//这里的timeout回覆盖之前的2.5S变成5s
instance.get('/longRequest',{
timeout: 5000
});
在发起请求前或者返回数据之前进行拦截和处理
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)
const instance = axios.create();
instance.interceptors.request.use(function () {/*...*/});
axios.get('/users/yxh')
.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);
});
axios.get('/users/yxh', {
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('/users/yxh', {
cancelToken: source.token
}).catch(function (thrown) {
if (axios.isCancel(thrown)) {
console.log('Request canceled', thrown.message);
} else {
// handle error
}
});
axios.post('/users/yxh', {
name: 'new name'
}, {
cancelToken: source.token
})
// 执行取消请求
source.cancel('Operation canceled by the user.');
const CancelToken = axios.CancelToken;
let cancel;
axios.get('/users/yxh', {
cancelToken: new CancelToken(function executor(c) {
// An executor function receives a cancel function as a parameter
cancel = c;
})
});
// cancel the request
cancel();
const params = new URLSearchParams();
params.append('param1', 'value1');
params.append('param2', 'value2');
axios.post('/foo', params);
const qs = require('qs');
axios.post('/foo', qs.stringify({ 'bar': 123 }));
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);
const querystring = require('querystring');
axios.post('https://cesi.huat.xyz/', querystring.stringify({ foo: 'bar' }));