fetch
fetch 浏览器提供的拥有底层交互能力的方法。
获取数据fetch,需要引入fetch.js
官方解释:fetch是window.fetch的JavaScript polyfill。全局fetch函数是web请求和处理响应的
简单方式,不使用XMLHttpRequest。这个polyfill编写的接近标准的Fetch规范。
get方式(默认)
fetch('***?id=*')
.then(function(data){
return data.json();
// return data.text();
})
.then(function(data){
console.log(data);
})
.catch((err)=>{
console.log(err);
})
.then 第一个 .then 处理响应结果,并返回处理之后的数据
.then 第二个 .then 得到处理之后的数据
post方式
fetch('***',{
method:'post',
body:JSON.stringify({})
})
axios
官方解释:Axios是一个基于promise的HTTP库,可以用在浏览器和node.js中。
特征:从浏览器中创建XMLHttpRequests
从node.js创建http请求
支持Promise API
拦截请求和响应
转换请求数据和响应数据
取消请求
自动转换JSON数据
客户端支持防御XSRF
获取数据axios,需要引入axios.js
get方式
axios.get('***')
.then(function(data){
console.log(data);
})
.catch(function(error){
console.log(error);
})
带有参数的get方式
axios.get('***',{
params:{
ID : 12345
}
})
.then(function(data){
console.log(data);
})
.catch(function(error){
console.log(error);
})
post方式
axios.post('***',{
firstName:'Fred',
lastName:'Flintstone'
})
.then(function(data){
console.log(data);
})
.catch(function(error){
console.log(error);
})
执行并发请求
function getUserAccount(){
return axios.get('***')
}
function getUserPermissions(){
return axios.get('***')
}
axios.all([getUserAccount(),getUserPermissions()])
.then(axios.spread(function(acct,perms){
// 两个请求现在都执行完成
}))
axios的默认选项全局配置
axios.defaults.baseUrl = '';
axios.defaults.headers.common['Authorization'] = AUTH_TOKEN;
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
带有headers的axios
登录:
login(){
axios({
url:'***',
method:'post',
data:{
userName:'admin',
password:'123456'
}
}).then((data)=>{
console.log(data.data);
localStorage.setItem('token',data.data.token)
})
}
获取用户信息,需设置headers,传token值
getinfo(){
axios({
url:'***',
headers:{
"authorizaion":"Bearer "+localStorage.getItem('token')
}
}).then((data)=>{
console.log(data.data);
})
}
请求拦截器
在请求或响应被 then 或 catch 处理前拦截它们。
// 添加请求拦截器
axios.interceptors.request.use(function(config){
// 在发送请求之前做些什么,如
if(localStorage.getItem('token')){
config.headers.common['authorization'] = "Bearer
"+localStorage.getItem('token');
}
return config;
},function(error){
// 对请求错误做些什么
return Promise.reject(error);
})
// 添加响应拦截器
axios.interceptors.response.use(function(response){
// 对响应数据做些什么,如,
console.log('收到响应信息')
console.log(response);
if(response.status==401){
// 跳转login
}else{
console.log('success')
}
return response;
},function(error){
// 对响应错误做些什么
return Promise.reject(error);
})