vue项目封装axios

106 阅读1分钟

Axios 是一个基于 promise 的网络请求库,可以用于浏览器和 node.js

在我写这个项目里面,请求接口主要有get和post还有delete方法,axios是基于promise的第三方库,引入安装好的axios,然后定义的一个变量,接收一个箭头函数,里面有有2个参数,一个是url,后面的是携带的参数,箭头函数里面返回的是一个pormise,然后后面用then().catch(),then里面也是一个箭头函数做参数,箭头函数里面是一个response,这上面有接口里面的数据,如果请求成功,返回response,失败的话,返回错误消息。如果是post请求,还要加上返回内容的格式。写在响应头里面。 'Content-type': 'application/json'

import axios from 'axios'
const instance = axios.create({
  baseURL:
    'https://www.fastmock.site/mock/74626af88f74409747775d86bd7db21d/weixin'
})

// 用axios调用接口
// 使用axios用post方式调用接口,以后,因为axios是基于promise
// 所以写法就是axios.post().then.catch()
// 封装post请求
const post = (url, data = {}) => {
  return new Promise((resolve, reject) => {
    instance
      .post(url, data, {
        headers: { 'Content-type': 'application/json' }
      })
      .then(
        (response) => {
          resolve(response)
        },
        (error) => {
          reject(error)
        }
      )
  })
}
// 封装get请求
const get = (url, params = {}) => {
  return new Promise((resolve, reject) => {
    // axios的返回值是一个promise,直接在axios()后面.then().catch()
    instance.get(url, { params }).then(
      (response) => {
        resolve(response)
      },
      (error) => {
        reject(error)
      }
    )
  })
}

export { post, get }