fetch和axios

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);
	})
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值