一、下載依賴包
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': '' } } }