api文件下的ajaxios
/* ajax請求函數模塊 返回值: promise對象(異步返回的數據是: response.data) */ import axios from 'axios' export default function ajax (url, data={}, type='GET') { return new Promise(function (resolve, reject) { // 執行異步ajax請求 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(function (response) { // 成功了調用resolve() resolve(response.data) }).catch(function (error) { //失敗了調用reject() reject(error) }) }) } /* const response = await ajax() const result = response.data const resule = await ajax() */
ajax文件下的index.jsgit
/* 包含n個接口請求函數的模塊 函數的返回值: promise對象 */ import ajax from './ajax' // 引入封裝好的請求函數 // const BASE_URL = 'http://localhost:4000' const BASE_URL = '/api' // 一、根據經緯度獲取位置詳情 export const reqAddress = (geohash) => ajax(`${BASE_URL}/position/${geohash}`) // 二、獲取食品分類列表 export const reqFoodCategorys = () => ajax(BASE_URL+'/index_category') // 三、根據經緯度獲取商鋪列表 export const reqShops = (longitude, latitude) => ajax(BASE_URL+'/shops', {longitude, latitude}) // 四、根據經緯度和關鍵字搜索商鋪列表 export const reqSearchShop = (geohash, keyword) => ajax(BASE_URL+'/search_shops', {geohash, keyword}) // 六、用戶名密碼登錄 export const reqPwdLogin = ({name, pwd, captcha}) => ajax(BASE_URL+'/login_pwd', {name, pwd, captcha}, 'POST') // 七、發送短信驗證碼 export const reqSendCode = (phone) => ajax(BASE_URL+'/sendcode', {phone}) // 八、手機號驗證碼登錄 export const reqSmsLogin = (phone, code) => ajax(BASE_URL+'/login_sms', {phone, code}, 'POST') // 九、根據會話獲取用戶信息 export const reqUserInfo = () => ajax(BASE_URL+'/userinfo') // 十、用戶登出 export const reqLogout = () => ajax(BASE_URL+'/logout') /** * 獲取商家信息 */ export const reqShopInfo = () => ajax('/info') /** * 獲取商家評價數組 */ export const reqShopRatings = () => ajax('/ratings') /** * 獲取商家商品數組 */ export const reqShopGoods = () => ajax('/goods')
配置代理ajax
在項目中使用axios