Vuejs技术栈--交互axios
安装
npm install --save axios
封装 ajax 请求模块 api/ajax.js
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
import axios from 'axios' export default function ajax(url = '', data = {}, type = 'GET') { return new Promise(function (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) }) }) }
接口请求函数的模块 api/index.js
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
/* 包含n个接口请求函数的模块 函数的返回值: promise对象 */ import ajax from './ajax' // const BASE_URL = 'http://localhost:4000' const BASE_URL = '/api' // 1、根据经纬度获取位置详情 export const reqAddress = (geohash) => ajax(`${BASE_URL}/position/${geohash}`) // 2、获取食品分类列表 export const reqFoodCategorys = () => ajax(BASE_URL+'/index_category') // 3、根据经纬度获取商铺列表 export const reqShops = (longitude, latitude) => ajax(BASE_URL+'/shops', {longitude, latitude}) // 4、根据经纬度和关键字搜索商铺列表 export const reqSearchShop = (geohash, keyword) => ajax(BASE_URL+'/search_shops', {geohash, keyword}) // 6、用户名密码登陆 export const reqPwdLogin = ({name, pwd, captcha}) => ajax(BASE_URL+'/login_pwd', {name, pwd, captcha}, 'POST') // 7、发送短信验证码 export const reqSendCode = (phone) => ajax(BASE_URL+'/sendcode', {phone}) // 8、手机号验证码登陆 export const reqSmsLogin = (phone, code) => ajax(BASE_URL+'/login_sms', {phone, code}, 'POST') // 9、根据会话获取用户信息 export const reqUserInfo = () => ajax(BASE_URL+'/userinfo') // 10、用户登出 export const reqLogout = () => ajax(BASE_URL+'/logout') /** * 获取商家信息 */ export const reqShopInfo = () => ajax('/info') /** * 获取商家评价数组 */ export const reqShopRatings = () => ajax('/ratings') /** * 获取商家商品数组 */ export const reqShopGoods = () => ajax('/goods')
配置代理config/index.js
api开头的解决跨域问题,不是api的可以被mockjs拦截,进行数据模拟
proxyTable: { '/api': { // 匹配所有以 '/api' 开头的请求路径 target: 'http://localhost:4000', // 代理目标的基础路径 changeOrigin: true, // 支持跨域 pathRewrite: {// 重写路径 : 去掉路径中开头的 '/api' '^/api': '' } }
Mockjs: 用来拦截 ajax 请求, 生成随机数据返回
安装
npm install mockjs --save
使用(mock/mockServer.js)
import Mock from 'mockjs' import apiData from './data.json' Mock.mock('/seller', {code:0, data:apiData.seller}) Mock.mock('/goods', {code:0, data:apiData.goods}) Mock.mock('/ratings', {code:0, data:apiData.ratings})