Axios学习和封装 - Go语言中文社区

Axios学习和封装


                                                         Axios学习和封装

一、axios的请求方法:get、post、put、patch、delete

get: 获取数据

post: 提交数据

put: 更新数据(表单提交 + 文件上传)

patch: 更新数据(只将修改的数据推送到后端)

delete: 删除数据

 

 

1、get方式

axios.get('url', {params: {id: 12}}).then(res => {

console.log(res)

})

 

axios({

method: 'get',

url: 'url',

params: {

id: 12

}

})

 

2、post方式(application/json方式、form-data方式【表单提交和文件、图片上传】),同样put、patch提交也具有application/json方式、form-data方式

(1)application/json方式

let data = {

id: 12

}

axios.post('url', data).then(res => {

console.log(res)

})

 

axios({

method: 'post',

url: 'url',

data: data

}).then(res => {

console.log(res)

})

(2) form-data请求

let data = {

id: 12

}

let formdata = new FormData()

for(let key in data) {

formdata.append(key, data[key])

}

axios.post('url', fromdata).then(res => {

console.log(res)

})

 

3、put请求

let data = {

id: 12

}

axios.put('url', data).then(res => {

console.log(res)

})

 

4、patch请求

let data = {

id: 12

}

axios.patch('url', data).then(res => {

console.log(res)

})

 

5、delete请求

(1)在url中传输,浏览器表现为Query String Paraeters

axios.delete('url', {params: {id: 12}}).then(res => {

console.log(res)

})

 

(2)不在url中传输,浏览器表现为Request Payoad对象形式

axios.delete('url', {data: {id: 12}}).then(res => {

console.log(res)

})

 

二、并发请求

定义: 同时进行多个请求,并统一处理返回值

axios.all(

[

axios.get('url1'),

axios.get('url2')

]

).then(

axios.spread((dataRes, cityRes) => {

console.log(dataRes, cityRes)

})

)

 

三、创建axios实例

针对后端接口地址有多个,并且超时时长不一样

let instance = axios.create({

baseURL: 'url',

timeout: 1000(若后端不返回数据,则前端返回401超时)

})

 

instance.get('url').then(res => {

console.log(res)

})

 

四、axios基本配置参数

axios.create({

baseURL: '', // 请求的域名,后端地址

timeout: 1000, //请求超时时长,及时释放资源,前端设置

url: '',// 请求路径

method: 'get, post, put, patch, delete', //请求方法

headers: {

token: '', // 请求头

},

params: {},// 请求参数拼接在url上

data: {} // 请求参数

})

 

1、全局配置, 优先级低

axios.defaults.timeout = 1000

axios.defaults.baseURL= 'http://loalhost:8080'

 

2、实例配置,优先级中

let instance = axios.create()

instance.defaults.timeout = 3000

 

3、请求配置,优先级高

instance.get('url', {timeout: 5000})

 

五、拦截器

拦截器: 在请求或响应被处理前拦截它们,所以分为请求拦截器和响应拦截器

1、请求拦截器

axios.interceptors.request.use(config => {

// 在发送请求钱做些什么

return config

}, err => {

// 在请求错误的时候做些什么

return Promise.reject(err)

})

 

2、响应拦截器

axios.interceptors.response.use(res=> {

// 请求成功对响应数据做处理

return res

}, err => {

// 在响应错误的时候做些什么

return Promise.reject(err)

})

 

3、取消拦截器(了解)

 

六、axios封装

1、contactApi.js

const  CONTACT_API = {
    // 获取路况列表
    getContactList: {
        method: 'get'
    },
    // 新建联系人 from-data
    newContactForm: {
        method: 'post'
    },
    // 新建联系人 application/json
    newContactJson: {
        method: 'put'
    },
    // 编辑联系人
    editContact: {
        method: 'put'
    },
    // 删除联系人
    deleteContact: {
        method: 'delete'
    }
}
export default CONTACT_API

 

2、http.js

import axios from 'axios'
import service from './contactApi'
import { Loading, Message } from 'element-ui'




let instance = axios.create({
    baseURL: 'http://www.baidu.com', // 服务器地址
    timeout: 1000
})




const Http = { // 包裹请求方法的容器




}




for (let key in service) {
    let api = service[key] // url和method
    // async作用: 避免进入回调地狱
    Http[key] = async function(
        url,
        params, //请求参数  get: url    delete: url   put、post、patch: data
        isFormData = false, //标识一下是否是form-data请求
        config = {} // 配置参数
    ) { 
        let newParams = {}
        // 判断content-type是否是form-data
        if (params && isFormData) {
            newParams = new FormData()
            for (let i in params) {
                newParams.append(i, params[i])
            }
        } else {
            newParams = params
        }




        // 不同请求的判断
        let response = {} // 请求返回值
        if (api.method === 'put' || api.method === 'post' || api.method === 'patch') {
            try {
                response = await instance[api.method](url, newParams, config)
            }catch(err){
                response = err
            }
        } else if (api.method === 'delete' || api.method === 'get') {
            config.params = newParams
            try {
                response = await instance[api.method](url, config)
            }catch(err){
                response = err
            }
        }
        return response //返回请求响应值
    }
}






//开始加载动画
let loading
function startLoading() {
    loading  = Loading.service({
        lock:true, // 是否锁定
        text:'拼命加载中...', // 加载中需要显示的文字
        spinner: 'el-icon-loading',
        background:'rgba(0,0,0,.7)' // 背景颜色
    })
}
//结束加载动画
function endLoading() {
    loading.close()
}






// 请求拦截起的添加
instance.interceptors.request.use(config => {
    // 发起请求前做些什么
    startLoading()
    return config
}, err => {
    // 请求错误
    endLoading()
    Message.error({
        message: '请求错误,请稍后重试'
    })
})




// 响应拦截器
instance.interceptors.response.use(res => {
    // 请求成功
    endLoading()
    return res.data
}, err => {
    endLoading()
    Message.error({
        message: '请求错误,请稍后重试'
    })
})

3、main.js

import Http from './service/http'


Vue.prototype.$http = Http

4、get请求调用展示在Home.vue

created() {
    this.getRoadList()
  },
methods: {
    async getRoadList() {
      let res = await this.$http.getContactList('/RoadStatus/list',{    offset: 0, limit: 10})
      if (res.code === 0) {
        this.roadList = res.data.rows
      }
    }
  }

 

版权声明:本文来源CSDN,感谢博主原创文章,遵循 CC 4.0 by-sa 版权协议,转载请附上原文出处链接和本声明。
原文链接:https://blog.csdn.net/u013144287/article/details/98076998
站方申明:本站部分内容来自社区用户分享,若涉及侵权,请联系站方删除。
  • 发表于 2020-03-07 15:39:40
  • 阅读 ( 818 )
  • 分类:

0 条评论

请先 登录 后评论

官方社群

GO教程

猜你喜欢