Vue中使用Ajax與後臺互動
阿新 • • 發佈:2021-06-28
一、下載依賴包
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