axios异步请求

本文介绍了axios的基础用法,包括GET和POST请求、配置选项、并发请求以及封装示例。重点讲解了如何设置请求头、数据处理和错误处理。并通过Vue实例展示了如何在项目中全局使用axios,配合拦截器实现请求和响应的定制化处理。
摘要由CSDN通过智能技术生成

1.认识axios

axios是一个易用,简洁且高效的基于Promise的http库,主要用于网络请求的服务,应用在浏览器或者NodeJS应用环境中

2.axios基本语法

axios是一个基于Promise的http库,用于完成网络请求的处理操作,支持常规的请求方式
基本语法:
get请求

axios.get('/user?id=1')
	.then(response=>{
		console.log(response)
	})
	.catch(err=>{
		console.log(err)
	})
axios.get('/user',params:{id:1})
.then(response=>{
		console.log(response)
	})
	.catch(err=>{
		console.log(err)
	})

post请求

axios.post('user',{
	id:1,
	uname:'张三'
})
.then(response=>{
		console.log(response)
	})
	.catch(err=>{
		console.log(err)
	})

并发请求(多个请求必须同时成功,才处理结果)

function getUserAccount(){
	return axios.get('/good/images/12')
}
function getUserPermiseeions(){
	return axios.get('/good/detail/12')
}
axios.all([getUserAccount(),getUserPermissions()])
.then(axios.spread(acct,perms)=>{}))

通用配置语法
发送POST请求

axios({
	method:'post',
	url:'/user/1',
	data:{
		id:1,
		uname:'张三'
	}	
})

axios配置选项中的常见配置项

{
	url: '/user',  //用于请求的服务器URL
	method:'get', //创建请求时使用的方法
	baseURL:'http://localhost:3000/', //设置一个baseURL,自定拼接在url前面
	transformRequest:[function(data,headers){ //允许在向服务器发送请求之前修改数据,后面数组中的函数必须返回一个字符串或ArrayBuffer,或Strem
		return data  //对data进行任意类型转换
	}],
	headers:{'X-Requested-With':'XMLHttpRequest'},  //为即将发送的数据设置请求头
	params:{id:1},//即将与请求一起发送的URL参数,必须是一个无格式对象(plain object)或URLSearchParams对象
	paramsSeriallizer:function(paramst){  //负责将params序列化函数
		return Qs.stringify(params,{arrayFormat:'brackets'}) 
	},
	data:{
		id:1   //作为请求主体被发送的数据
	},
	timeout:1000,  //指定请求超时的毫秒数,如果请求花费了超过'timeout'时间,请求将被中断
	withCredentials:false, //default 表示跨域请求时是否要使用凭证
	adapter:function(config){  //允许自定处理请求,返回一个oromise并应用一个有效的响应
	},
	auth:{    //表示使用HTTP基础验证,并提供凭证,设置一个Authorization头,覆写掉现有的任意使用headers设置的自定的Authorization头
		username:'zhangsan',
		password:'sdahio'
	},
	responseType:'json', //表示服务器响应的数据类型
	responseEncoding:'utf8', 
	xsrfCookieName:'XSRF-TOKEN', //用作xsrf token的值的cookie的名称
	xsrfHeaderName:'X-XSRF-TOKEN', 
	onUploadProgress:function(progressEvent){
			//允许为上传处理进度事件
	},
	onDownloadProgress:function(progressEvent){
		//对原生进度事件的处理
	},
	maxContentLength:2000, // 定义允许的响应内容的最大尺寸
	validateStatus:function(status){
		return status >= 200 && status < 300 // 定义对于给定的HTTP 响应状态码是 resolve 或 reject  promise 。如果 `validateStatus` 返回 `true` (或者设置为 `null` 或 `undefined`),promise 将被 resolve; 否则,promise 将被 rejecte
	},
	maxRedirects:5, //定义在node.js中follow的最大重定向数目
	sokectPath:null, 
	httpAgent:new http.Agent({keepAlive:true}),
	httpsAgent:new https.Agent({keepAlive:true}), // `httpAgent` 和 `httpsAgent` 分别在 node.js 中用于定义在执行 http 和 https 时使用的自定义代理。允许像这样配置选项:
	proxy:{
		host:'localhost',
		port:'3000',
		auth:{
			username:'mikeymike',
			password:'sahoih'     // 'proxy' 定义代理服务器的主机名称和端口
  // `auth` 表示 HTTP 基础验证应当用于连接代理,并提供凭据
  // 这将会设置一个 `Proxy-Authorization` 头,覆写掉已有的通过使用 `header` 设置的自定义 `Proxy-Authorization` 头。
		}
	},
	cancelToken:new CancelToke(function(cancel){})
}

axios会自动将服务器返回的数据进行封装,按照标准格式返回数据,格式如下

{
	data:{}, //服务器接口返回的真实数据,重点关注data即可
	status:200, //来自服务器响应的HTTP状态码
	statusText:'OK',  //来自服务器响应的HTTP状态信息
	headers:{},  //服务器响应头
	config:{}, //为请求提供的配置信息
	requet:{}
}

axios提供了请求和响应数据之间的,网络数据拦截功能:请求拦截器、响应拦截器

//添加请求拦截器
axios.interceptors.request.use(function(config){
	return config
},function(error){
	return Promise.reject(error)
})
//添加响应拦截器
axios.interceptors.response.use(function(response){
	return response
},function(error){
	return Promise.reject(error)
})

3.axios封装

import Vue from 'Vue'
import axios from 'axios'
const instance = axios.create({
	baseURL:'http://localhost:3000/goods',
	headers:{'myname':'myvalue'}
})
//封装,添加请求和响应拦截器
instance.interceptors.request.use(request=>{
	console.log('拦截到请求',request)
	return request
})
instance.interceptors.responese.use(response=>{
	return response.data
})
Vue.prototype.$http = instance
export default instance
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值