vue-ajax/axios请求函数封装: axios+promise

项目文件目录/src/api

ajax.js

/**
 * ajax 请求函数模块
 * 返回值为promise对象
 */
import axios from 'axios'
export default function ajax (url, data = {}, type = 'GET') {
  return new Promise((resolve, reject) => {
    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)
      })
  })
}

index.js

举例:接口请求函数封装: 每个后台

/**
 * 包含n个接口函数的模块
 * 返回值为promise对象
 *
 * 1、根据经纬度获取位置详情
 * 2、获取食品分类列表
 * 3、根据经纬度获取商铺列表
 * 4、根据经纬度和关键字搜索商铺列表
 * 5、获取一次性验证码
 * 6、用户名密码登陆
 * 7、发送短信验证码
 * 8、手机号验证码登陆
 * 9、根据会话获取用户信息
 * 10、用户登出
 */
import ajax from './ajax'

// 1、根据经纬度获取位置详情
export const reqAddress = (geohash) => ajax(`/position/${geohash}`)

// 2、获取食品分类列表
export const reqFoodTypes = () => ajax('/index_category')

// 3、根据经纬度获取商铺列表
export const reqShops = (latitude, longitude) => ajax('/shops', {
  latitude,
  longitude
})

// 4、根据经纬度和关键字搜索商铺列表
export const reqShopsSearch = (geohash, keyword) => ajax('/search_shops', {
  geohash,
  keyword
})

// 5、获取一次性验证码
export const reqCaptcha = () => ajax('/captcha')

// 6、用户名密码登陆
export const reqPwdLogin = (name, pwd, captcha) => ajax('/api/login_pwd', {
  name,
  pwd,
  captcha
}, 'POST')

// 7、发送短信验证码
export const reqSendCode = phone => ajax('/api/sendcode', {
  phone
})

// 8、手机号验证码登陆
export const reqSmsLogin = (phone, code) => ajax('/api/login_sms', {
  phone,
  code
}, 'POST')

// 9、根据会话获取用户信息
export const reqUser = () => ajax('/api/userinfo')

// 10、用户登出
export const reqLogout = () => ajax('/api/logout')

原文地址:https://www.cnblogs.com/izhaong/p/12154304.html