axios框架的使用 (网络请求相关)

1、特点

  • 支持浏览器和node.js
  • 支持promise
  • 能拦截请求和响应
  • 能转换请求和响应数据
  • 能取消请求
  • 自动转换JSON数据
  • 浏览器端支持防止CSRF(跨站请求伪造)

2、安装

用npm:

npm install axios

 用 bower:

bower install axios

 用cdn

<script src="https://unpkg.com/axios/dist/axios.min.js"></script>

 3、使用

<script>
// 1、axios的基本使用(默认请求是get)
axios({
    url:'http://127.0.0.1:8000/home/muitls/',
    // method: 'get',
}).then(res => {
    console.log(res.data)
})

// 请求的参数拼接
axios({
    url: 'http://127.0.0.1:8000/home/?gid=' + this.god_id
}).then(res => {
    console.log(res.data)
})

// 写法一
axios({
    url: 'http://127.0.0.1:8000/home/data/',
    // 专门针对get请求的参数拼接
    params:{
        'type': pop,
        'page': 1
    }
}).then(res => {
    console.log(res.data)
})

//写法二
axios.get("http://127.0.0.1:8000/home/multidata",{
    params:{
        type: 'pop',
        page: 1
    }
}).then(res => {
    console.log(Res.data)
}).catch(err => {
    console.log(err)
})

// post请求
axios.post("http://127.0.0.1:8000/home/multidate",{
    firstName: 'Fred',
    lastName: 'Flintstone'
}).then(res => {
    console.log(res)
})

axios({
    url: '/adv/login/',
    method:'post',  // 需要指定请求参数
    data: {  // 注意get请求是params
        username: 'lan',
        password: '123'
    }
}).then(res => {
    console.log(res)
}).catch(err => {
    console.log(err)
})

// 3、axios发送并发请求
axios.all([axios({
    url: 'http://127.0.0.1:8000/home/multidata'
}),axios({
    url: 'http://127.0.0.1:8000/home/data',
    params:{
        type: 'sell',
        page: 5
    }
})]).then(res => {
    console.log(res)
})

//展示结果 axios.spread()
axios.all([axios({
    url: 'http://127.0.0.1:8000/home/multidata'
}),axios({
    url: 'http://127.0.0.1:8000/home/data',
    params:{
        type: 'sell',
        page: 5
    }
})]).then(axios.spread((res1,res2) => {
    console.log(res1);
    console.log(res2)
}))
</script>

 4、配置信息相关

<script>
// 使用全局的axios和对应的配置进行网络请求
axios.defaults.baseURL = 'http://127.0.0.1:8000/'
axios.defaults.timeout = 5000

axios.all([axios({
  url:'home/multidata'
}),axios({
  url:'home/data',
  params:{
    type:'sell',
    page:5
  }
})]).then(axios.spread((res1,res2) => {
  console.log(res1);
  console.log(res2);
}))
</script>

5、常见的配置选项

 项目前景(模块化封装):在项目开发中,当我们在不同的页面中需要请求数据时可能会这样做,但是这样的话,每个请求的页面都需要引入axios框架,当axios框架不在维护或者有重大bug时,需要修改替换成例外的框架。这时会发现需要在每个页面都修改,这样太费劲了。

 

6、封装request模块 

在src目录下新建network文件夹,然后在该文件夹里新建一个request.js在这里插入图片描述

(注:页面中不需要在引入axios框架啦!)

在这里插入图片描述

在这里插入图片描述

7、axios请求拦截器和响应拦截器

axios里面可以设置拦截器 ,在请求发送之前做一些事情;
拦截器分【请求拦截器】和【响应拦截器】
参考地址:https://www.jb51.net/article/150014.htm
参考的地址:https://www.jianshu.com/p/7bc7654d4574

请求拦截器的实际应用场景
在进行鉴权的时候;我们每个接口都需要携带token;
难道每次我们都需要手动拼接token;
这个时候拦截器就很有用了;
这时候就可以用拦截器来使token自动增加


// 首先我们看下请求拦截器的写法;在请求或响应被 then 或 catch 处理前拦截它们。
<script>
axios.interceptors.request.use((config)=>{
	console.log("--",config);
	config.baseURL="http://127.0.0.1:8000/";
	
                if (token) {  // 判断是否存在token,如果存在的话,
                              //则每个http header都加上token
                     config.headers.myAuthorization = mytoken;
	            // config.headers['Authorization'] = token;
                } 
	       if(!config.hasOwnProperty('showError')){
	            config.showError = true
               }
	return config;
},(err)=>{
    console.log(error)
     // 发生错误做的一些事情
      return Promise.reject(error);
})



// 添加响应拦截器
axios.interceptors.response.use(function (res) {
  // 对响应数据做点什么
   if (res&&res.data&&res.data.success) {
                return  res.data
   }else{
	if(res.config.showError) {
                  //如何请求失败,开启了错误提示;进行提示
                    window.$toast(res.data.msg)
                }
                return Promise.reject(res.data)
  }}, function (error) {
     // 对响应错误做点什么;没有权限401,去登录界面
     if(error.response.status === 401) {
            window.$toast('登录超时')
            setTimeout(() => {
                uni.switchTab({  
                    url: '/pages/home/home'
                })
            },1000)
        }else if(error.response.status === 403) {
            window.$toast('暂无权限')
        }else {
            window.$toast('网络错误')
        }

  return Promise.reject(error);
 });

export default axios
</script>

 8、使用

<script>
import request from './common'
/** 
{请求参数} data   
@param {
showError: 是否隐藏错误提醒
 } utils 
*/


export function getUserInfo(data, utils) {
	return request({
		url: 'xxx/xx/user',
		method: 'get',
		data,
		...utils
	})
}
</script>
Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐