记录一次Vue中使用axios进行网络请求。起初封装很简单,只包含get
和post
两种请求接口:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35
| import axios from 'axios'
export function get(url, params) { return new Promise((resolve, reject) => { axios.get(url, { params: params }).then(res => { resolve(res); }).catch(err => { reject(err) }) }); }
export function post(url, params) { return new Promise((resolve, reject) => { axios.post(url, QS.stringify(params)) .then(res => { resolve(res); }) .catch(err => { reject(err) }) }); }
|
使用时:
1 2 3 4 5 6 7
| import { get, post } from './http/http'
var url = 'http://localhost:10119/idiom/queryStoryByWord?word=%E6%9C%9D%E4%B8%89%E6%9A%AE%E5%9B%9B';
get(url).then((response) => { console.log(response) })
|
后经过一次更新升级:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52
| import axios from 'axios'
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded'
axios.defaults.baseURL = '//localhost:10119'
export default function request(url, type = 'GET', data = {}) { return new Promise((resolve, reject) => { let option = { url, method: type, } if(type.toLowerCase() === 'get') { option.params = data }else { option.data = data } if(localStorage.token) { axios.defaults.headers.common['Authorization'] = localStorage.token }
axios(option).then(res => { if(res.status===200 && res.data.code === 0) { if(res.data.token) { localStorage.token = res.data.token } resolve(res.data) }else{ reject(res.data) } }).catch(err => { reject({ msg: '网络异常:'+err }) }) }) }
|
1 2 3 4 5 6 7 8 9 10 11 12 13
| import request from './request.js'
const URL = { GET_IDIOM_BY_ID: '/idiom/queryById' };
export default { queryById({ id }) { return request(URL.GET_IDIOM_BY_ID, 'GET', { id }); }, };
|
使用时:
1 2 3 4 5
| import api from './http/api.js'
api.queryById({id:3506}).then(data => { console.log(data); })
|
这样做的好处是后续只需要维护好业务访问接口api.js
就好。