zoukankan      html  css  js  c++  java
  • 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')
    
    
  • 相关阅读:
    自己写的基类:Forms身份验证类、客户端事件类,序列化类下载
    毕业设计上线啦!跳蚤部落与基于Comet的WebIM系统开发
    域名解析碎片整理 《不同的子域名解析到同一服务器下不同的网站》
    Mac 命令行大全
    position 事件 zindex
    vue 微信公众号网页开发 跳转小程序 踩坑
    React 笔记
    我对架构师的理解(如何成为一个合格的架构师)
    听过我爸是李刚,你听说过我妈是上海人不?
    Lucene.NET打造站内搜索引擎
  • 原文地址:https://www.cnblogs.com/izhaong/p/12154304.html
Copyright © 2011-2022 走看看