axios初识
1. axios.get(url)返回的是一个promise对象,若成功则PromiseState为fulfilled,若失败PromiseState为rejected,而PromiseResult则为获得的数据
console.log(axios.get('https://api.apiopen.top/getJoke'));
console.log(axios.get('https://api.apiopen.top/getJoke1'));
2.axios.get(url).then(value=>{}).catch(reason=>{})相当于是axios.get(url).then(value=>{},reason=>{});
axios.get('https://api.apiopen.top/getJoke1').then(value => {
console.log(value);
}, reason => {
console.log(reason);
})
相当于:
axios.get('https://api.apiopen.top/getJoke1').then(value => {
console.log(value);
}).catch(reason => {
console.log(reason);
})
3.then()中的参数可以为一个
一般value来表示成功的数据
axios.get('https://api.apiopen.top/getJoke1?ID=12345').then(value => {
console.log(value)
})
一般用reason来代表失败的原因
axios.get('https://api.apiopen.top/getJoke1?ID=12345').then(null, reason => {
console.log(reason);
})
4.向给定ID的url发起请求
axios.get('https://api.apiopen.top/getJoke?ID=12345')
相当于:
axios.get('https://api.apiopen.top/getJoke', {
params: {
ID: 12345
}
})
支持async/await用法
async function getUser() {
try {
const response = await axios.get('https://api.apiopen.top/getJoke?ID=12345');
console.log(response);
} catch (error) {
console.error(error);
}
}
getUser()
5.then方法执行完之后有一个返回值,返回的是一个新的Promise对象,所以可以使用链式方法继续调用then方法
axios.get('https://api.apiopen.top/getJoke').then(value => {
console.log(value);
}).catch(reason => {
console.log(reason);
}).then(function() { // 总是会执行
console.log(this) //window对象
});
6.常用请求配置
axios.defaults.baseURL = 'http://127.0.0.1:8000'; //配置baseURL(也可以写在里面,见下面)
axios({
//请求方法
method: 'POST', //不写默认是GET
//url
url: '/axios',
//配置 baseURL
//baseURL: 'https://some-domain.com/api/',
//url参数
params: {
vip: 10,
level: 30,
},
//请求头信息
headers: { //中文会报错,头信息里面不能写中文
a: 100,
b: 200,
},
//请求体参数
data: {
username: 'admin',
password: 'admin',
},
responseType: 'json', // 默认值
withCredentials: false, // withCredentials 表示跨域请求时是否需要使用凭证
// timeout 指定请求超时的毫秒数。
timeout: 1000, // 默认值是 `0` (永不超时) , 如果请求时间超过 `timeout` 的值,则请求会被中断
}).then(response => {
//响应状态码
console.log(response.status);
//响应状态字符串
console.log(response.statusText);
//响应头信息
console.log(response.headers);
//响应体
console.log(response.data);
})
}
7.全局 axios 默认值
axios.defaults.baseURL = '请求的域名';//其他地方请求地址可以省略域名
axios.defaults.headers.common['Authorization'] = AUTH_TOKEN;//表示作者认证,有时需要跟第三方做交互,认证--一般不会涉及
get请求不存在设置content-type。只有post和put用到content-type
post的content-type三种类型:
1.Content-Type: application/json
对于axios,post的时候axios.post(url,{a:1,b:2}),第二个参数是对象的时候,默认是这个类型
2.Content-Type: application/x-www-form-urlencoded
对于axios,post的时候let data = {a:1,b:2}; axios.post(url,qs.stringify({ data })),
第二个参数是字符串的时候,默认是这个类型
3.Content-Type: multipart/form-data
对于axios,post的时候let data = new FormData(); data.append('a',1'); data.append('b',2); axios.post(url,data),
参数是formData类型的时候,默认是这个类型,如果用form自带的action提交,默认是这个类型
因为后端要求的 'Content-Type': 'application/x-www-form-urlencoded' 为多见,
故如果传进去的参数不是字符串类型则需要另外配置
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
或
{headers:{'Content-Type':'application/x-www-form-urlencoded'}}
或
axios.defaults.transformRequest = [function(data, headers) {
if (data instanceof FormData) return data;
else if (data instanceof Object) return Qs.stringify(data);
else return data;
}];
8.拦截器:在请求或响应被 then 或 catch 处理前拦截它们
// 添加请求拦截器
axios.interceptors.request.use(function (config) {
// 在发送请求之前做些什么 // 这里可以加统一的参数,appid,token这类的
return config;
}, function (error) {
// 对请求错误做些什么
return Promise.reject(error);
});
// 添加响应拦截器
axios.interceptors.response.use(function (response) {
// 2xx 范围内的状态码都会触发该函数。
// 对响应数据做点什么
return response;
}, function (error) {
// 超出 2xx 范围的状态码都会触发该函数。
// 对响应错误做点什么
return Promise.reject(error);
});