axios的几种写法

一、axios介绍
1.axios:是一个简易,简洁且高效的网络请求库http库;它基于promise
2.axios的特点
支持promise 使用promise管理异步,告别传统的callback方式
支持node端和浏览器端:同样的Api,node和浏览器全支持,平台切换无压力
丰富的配置项,支持拦截器等高级配置
从浏览器中创建xmlhttprequests;
3.实例
image

一、执行get 请求
写法一、//为指定id用户的user创建请求
axios.get('/user?ID=12345')
.then(function(respose){
console.log(response);
})
.catch(function(err){
console.log(error);
})
写法二、
//上面的请求也可以这样做
axios.get('/user',{
params:{
ID:12345
}
})
.then(function(response{
console.log(response);
})
.catch(function(error){
console.log(error)
});
)
二、执行post请求
axios.post('/user',{
firstName:'Fred',
lastName:'Flintstone'
})
.then(function(response{
console.log(response);
})
.catch(function(error){
console.log(error);
});
image

	 三、执行多个并发的请求
	 function getUserAccount(){
	 return axios.get('/user/12345');
	 }
	 function getsuerpermissions(){
	 return axios.get('/user/12345/permissons');
	 }
	 axios.all([getUserAccount(),getUserPermissions()])
	 .then(axios.spread(function(acct,perms){
	 //两个请求现在都执行完成
	 }));
	 
	 
	 四、用promise封装axios
	 在实际项目里为了更方便使用axios获取后台数据,在这里进行封装,src下的新建一个utils(存放工机具类函数)文件夹,index.js文件
	 import axios from 'axios';
	 //const get =()=>{
	 //   console.log('get请求');
	 //}
	 
	 //const post=()=>{
	 conosle.log('post请求')
	 }
	 
	 //export{
	 //get,
	 //post
	 //}
	 //
	 let baseURL;
	 if(process.env.NODE_ENV=='development'){
	 baseURL='http://.../api'
	 }else{
	 baseURL='/xxx'
	 }
	 //baseURL es6 方法
	 
	 const $http=axios.create({
	 baseURL,
	 })
	 //create是axios 自带的方法
	 
	 export const get=(url,params)=>{
	 params=params ||{};
	 return new Promise((resolve,reject)=>{
	 //axios自带get 和post方法
	 $http.get(url,{
	 params,
	 }).then(rs=>{
	 if(res.data.status===0){
	 resolve(res.data);
	 }else{
	 alert(res.data.msg)
	 }
	 }).catch(error=>{
	 alert('网络异常')
	 })
	 })
	 }
	 
	 export const post =(url,params)=>{
	 params=params ||{};
	 return new Promise ((resolve,reject)=>{
	 $http.post(url,params).then(res=>{
	 if(res.data.status===0){
	 resolve(res.data);
	 }else{
	 alert(res.data.msg);
	 }
	 }).catch(error=>{
	 alert('网络异常');
	 })
	 })
	 }
	 
	 main.js文件中做一下配置
	 import {get,post} from "./utils/index";
	 Vue.prototype.$http={
	 get,
	 post
	 };
	 
	 
	 (1)上述使用了构造函数的原型prototype(vue属于构造函数);

(2)声明一个全局变量并且把封装好的get和post方法放在里面。

使用封装后的函数:

created() {
this.getFilmList();
},
methods: {
async getFilmList() {
const url = "/film/getList";
// 要访问第二页的话在网址后面加 ?type=2&pageNum=页数
const res = await this.$http.get(url);
this.filmList = res.films;
},
注意:因为是promise封装的函数方法,所以使用的时候要加上async 函数(){ await 数据} 不然会报错,因为没有完成异步转同步。

posted @ 2022-07-03 21:07  月花夕沉  阅读(2162)  评论(0)    收藏  举报