vue中使用axios时封装公共方法(响应拦截器,请求拦截器)

古城微笑少年丶 2021-09-01 07:58 594阅读 0赞
  1. npm install axios --save
  2. //安装依赖

与main.js平行处创建http.js文件

  1. import axios from 'axios'
  2. axios.defaults.timeout = 60000; //响应时间
  3. //配置请求头
  4. axios.defaults.headers = {
  5. //公共请求头配置
  6. '属性':'这是是公共请求头的配置'
  7. }
  8. axios.defaults.baseURL = ''; //配置接口地址
  9. //POST传参序列化(添加请求拦截器)
  10. axios.interceptors.request.use((config) => {
  11. //在发送请求之前做某件事
  12. if(config.method === 'get'){
  13. config.data = true;
  14. }
  15. if(sessionStorage.getItem('token')){
  16. let token = sessionStorage.getItem('token')
  17. //已经登录
  18. config.headers['Content-Type'] = 'application/json;charset=UTF-8';
  19. config.headers['鉴权属性'] = token;
  20. }
  21. return config;
  22. },(error) =>{
  23. // console.log('错误的传参')
  24. return Promise.reject(error);
  25. });
  26. //返回状态判断(添加响应拦截器)
  27. axios.interceptors.response.use((res) =>{
  28. //对响应数据做些事
  29. if(!res.data.success){
  30. return Promise.resolve(res);
  31. }
  32. return res;
  33. }, (error) => {
  34. if(error.response.status == 401){
  35. //授权过期
  36. location.href = '/login'
  37. }
  38. return Promise.reject(error);
  39. });
  40. //返回一个Promise(发送post请求)
  41. export function fetchPost(url, params,config) {
  42. return new Promise((resolve, reject) => {
  43. axios.post(url, params,config)
  44. .then(response => {
  45. resolve(response);
  46. }, err => {
  47. reject(err);
  48. })
  49. .catch((error) => {
  50. reject(error)
  51. })
  52. })
  53. }
  54. 返回一个Promise(发送get请求)
  55. export function fetchGet(url,config, param) {
  56. return new Promise((resolve, reject) => {
  57. axios.get(url, config,{params: param})
  58. .then(response => {
  59. resolve(response)
  60. }, err => {
  61. reject(err)
  62. })
  63. .catch((error) => {
  64. reject(error)
  65. })
  66. })
  67. }
  68. export default {
  69. fetchPost,
  70. fetchGet,
  71. }

在main.js中引入

  1. import { fetchPost,fetchGet } from './http.js'
  2. Vue.prototype.getHttp = fetchGet;
  3. Vue.prototype.postHttp = fetchPost;

在组件中调用

  1. this.getHttp(url,config, param:{传值})
  2. this.getHttp(this.url,{params:{id:this.id}}).then((res)=>{}).catch((err)=>{})
  3. this.postHttp(url,params,config) params为传值
  4. this.postHttp(this.url,{id:this.id}).then((res)=>{}).catch((err)=>{})
  5. config为配置单独的header
  6. 传入格式
  7. {
  8. header:{
  9. 配置项
  10. }
  11. }

发表评论

表情:
评论列表 (有 0 条评论,594人围观)

还没有评论,来说两句吧...

相关阅读

    相关 axios拦截使用方法

    vue中axios获取后端接口数据有时候需要在请求开始时显示loading,请求结束后隐藏loading,这时候到每次调接口时都写上有点繁琐,有时候还会漏写。 这时候axio