美文网首页
Vue 封装axios,返回指定的response

Vue 封装axios,返回指定的response

作者: 领带衬有黄金 | 来源:发表于2019-10-15 14:41 被阅读0次

1. 需求

定制请求,将get,post方式进行封装axios,传参都以对象方式传递

2. ajax.js

/*
* ajax 请求函数模块
* 作用:对ajax的两种方法进行封装,只需要传入url,对象参数,请求方式
* 返回值:promise对象(异步返回的数据是:response.data)
* */
import axios from 'axios'

export default function ajax(url = '', data = {}, type = 'GET') {
  return new Promise(function (resolve, reject) {
      //执行异步ajax请求
      let promise
      if (type === 'GET') { // 准 备 url query 参 数 数 据
        let dataStr = '' // 数 据 拼 接 字 符 串
        Object.keys(data).forEach(key => {
          dataStr += key + '=' + data[key] + '&'
        })
        if (dataStr !== '') {
          dataStr = dataStr.substring(0, dataStr.lastIndexOf('&'))
          url = url + '?' + dataStr
        } //发送get 请 求
        promise = axios.get(url)
      } else { // 发 送 post 请 求
        promise = axios.post(url, data)
      }
      promise.then(response => {
        //成功的回调函数
        resolve(response.data)
      }).catch(error => {
        //失败的回调函数
        reject(error)
      })
    }
  )
}

  1. 请求使用

/*
* 包含n个接口请求函数的模块,向外暴露异步请求函数
* 函数的返回值:promise对象
* */
import ajax from './ajax'

// const BASE_URL = 'http://localhost:4000'
const BASE_URL = '/api'
// 1、根据经纬度获取位置详情
export const getAddress = (geohash) => ajax(`${BASE_URL}/position/${geohash}`)
// 2、获取食品分类列表
export const getFoodCategory = () => ajax(`${BASE_URL}/index_category`)
// 3、根据经纬度获取商铺列表
export const getShopList = (longitude, latitude) => ajax(`${BASE_URL}/shops`, {longitude, latitude})
// 4、根据经纬度和关键字搜索商铺列表
export const getSearchShops = (geohash, keyword) => ajax(`${BASE_URL}/search_shops`, {geohash, keyword})
// 6、用户名密码登陆
export const postPwdLogin = ({name, pwd, captcha}) => ajax(`${BASE_URL}/login_pwd`, {name, pwd, captcha}, 'POST')
// 7、发送短信验证码
export const getSendCode = (phone) => ajax(`${BASE_URL}/sendcode`, {phone})
// 8、手机号验证码登陆
export const postSmsLogin = (phone, code) => ajax(`${BASE_URL}/login_sms`, {phone, code}, 'POST')
// 9、根据会话获取用户信息
export const getUserInfo = () => ajax(`${BASE_URL}/userinfo`)
// 10、用户登出
export const getLogout = () => ajax(`${BASE_URL}/logout`)

/*---------------mock假数据----------------*/
// 获取商家信息
export const getShopInfo = () => ajax('/info')

// 获取商家评价数组
export const getShopRatings = () => ajax('/ratings')

// 获取商家商品数组
export const getShopGoods = () => ajax('/goods')

相关文章

网友评论

      本文标题:Vue 封装axios,返回指定的response

      本文链接:https://www.haomeiwen.com/subject/ayojmctx.html