Vue中使用Ajax与后台交互

一、下载依赖包

npm install --save axios

二、封装 ajax 请求模块

2.1 api/ajax.js

/*
ajax 请求函数模块
 */
import axios from 'axios'

export default function ajax (url = '', data = {}, type = 'GET') {
  return new Promise(function (resolve, reject) {
    let promise

    if (type === 'GET') {
      let dataStr = ''
      Object.keys(data).forEach(key => {
        dataStr += key + '=' + data[key] + '&'
      })
      if (dataStr !== '') {
        dataStr = dataStr.substring(0, dataStr.lastIndexOf('&'))
        url = url + '?' + dataStr
      }
      promise = axios.get(url)
    } else {
      promise = axios.post(url, data)
    }

    promise.then(response => {
      resolve(response.data)
    }).catch(error => {
      reject(error)
    })
  })
}

2.2 api/index.js

/*
与后台交互模块
 */
import ajax from './ajax'

/**
 * 根据经纬度获取位置详情
 */
export const reqAddress = geohash => ajax('/api/position/' + geohash)

/**
 * 获取食品分类列表
 */
export const reqCategorys = () => ajax('/api/index_category')

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

/**
 * 获取一次性验证码
 */
export const reqCaptcha = geohash => ajax('/api/position/' + geohash)

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

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

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

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

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

三、配置代理

proxyTable: {
    '/api': { // 匹配所有以 '/api' 开头的请求路径
        target: 'http://localhost:4000', // 代理目标的基础路径
        changeOrigin: true, // 支持跨域
        pathRewrite: { // 重写路径:去掉路径中开头的'/api'
            '^/api': ''
        }
    }
}    
原文地址:https://www.cnblogs.com/mxsf/p/10877704.html