vue2 + axios http请求封装

简介: vue2 + axios http请求封装

此版本封装主要是对请求封装,拦截什么的没做处理。主要是处理了请求的方式是post还是get请求做了处理,新建一个http.js,代码如下:

import Qs from 'qs'
import axios from "axios"
axios.defaults.timeout = 15000;
axios.defaults.transformResponse = [function (data) {
  data = JSON.parse(data)
  return data
}]
axios.interceptors.request.use(function(config) {
  console.log("请求开始")
  return config;
}, function (error) {
  return Promise.reject(error);
});
axios.interceptors.response.use((res) => {
  console.log("请求结束 ")
  return res;
}, (error) => {
  return Promise.reject(error);
});
function http(type,url, params,contentType) {
  let contType = contentType=='json' ? 'application/json':'application/x-www-form-urlencoded'
  let paramstranform = contentType == 'json' ? params : Qs.stringify(params)
  if(type == "get"){
    return new Promise((resolve, reject) => {
      // alert("axios-token:::"+localStorage.token)
      axios({
        method:'get',
        url:url,
        headers: {'token' : localStorage.token},
        params:params
      })
      // axios.get(url, { params: params },{headers : {'token' : localStorage.token}})
      .then((res) => {
        resolve(res.data)
      }).catch(err => {
        if (err == "Error: timeout of 15000ms exceeded") {
          console.log("服务器请求超时")
          return
        }
        alert(err)
      })
    })
  }else{
    return new Promise((resolve,reject)=>{
       axios({
        method:'post',
        url:url,
        headers: {'Content-Type': contType},
        data:paramstranform
      })
      // axios.post(url,paramstranform,{headers:{'Content-Type': contType,'token' : localStorage.token}})
      .then((res)=>{
        resolve(res.data)
      }).catch(err=>{
        if(err == "Error: timeout of 15000ms exceeded"){
          alert("服务器请求超时,请刷新页面重新进入")
        }
        alert(err)
      })
    })
  }
}
export default http

在在main.js里引用

import httpRequest from '@/config/http'  具体的地址还有文件名自己改写
Vue.prototype.$http = httpRequest //定义一个全局变量

在文件或者模板文件里运用如下;

getList(){
        this.$http('post',this.baseUrl+'/tag/theme/list').then((res) => {
           console.log(res)
        });
}


相关文章
|
17天前
|
JSON 前端开发 JavaScript
3分钟让你学会axios在vue项目中的基本用法(建议收藏)
3分钟让你学会axios在vue项目中的基本用法(建议收藏)
47 0
|
23天前
|
前端开发 API
Axios请求成功和失败时分别执行哪个函数?
Axios请求成功和失败时分别执行哪个函数?
16 1
|
2月前
|
JSON 数据格式
使用axios发送get和post请求
使用axios发送get和post请求
32 0
|
8天前
axios封装和配置
axios封装和配置
16 0
|
14天前
axios中的get带参数的请求方法
axios中的get带参数的请求方法
|
17天前
|
JavaScript API
Vue中axios拦截器怎么使用
Vue中axios拦截器怎么使用
|
1月前
|
Web App开发 前端开发 JavaScript
Spring Boot整合 mybatisplus(后端) Vue+echarts+Element UI+axios(前端)---前后端项目实例demo
Spring Boot整合 mybatisplus(后端) Vue+echarts+Element UI+axios(前端)---前后端项目实例demo
27 1
|
1月前
|
前端开发 JavaScript Java
springboot+mybatis plus+vue+elementui+axios 表格分页查询demo
springboot+mybatis plus+vue+elementui+axios 表格分页查询demo
32 0
|
1月前
|
资源调度 JavaScript 前端开发
|
1月前
|
数据采集 JavaScript 前端开发
利用axios库在Node.js中进行代理请求的实践
利用axios库在Node.js中进行代理请求的实践