在vue2.0中使用axios向后台请求数据
全局配置axios, /src/apis/index.js
import axios from 'axios';
import qs from 'qs';
axios.defaults.baseURL = 'http://usergroup.laile.com/api_group/v1/';
axios.defaults.timeout = 5000;
axios.interceptors.request.use((config) => {
if(config.method === 'post') {
config.data = qs.stringify(config.data);
}
}, (error) => {
return Promise.reject(error);
});
axios.interceptors.response.use((res) => {
if(!res.data.success) {
return Promise.reject(res);
}
return res;
}, (error) => {
return Promise.reject(error);
});
export default axios;
/src/apis/mountedUsers.js 某个页面的接口文件
import axios from './index';
export default {
getCities() {
return axios.get(`/city/opened-list`);
}
}
/src/store/modules/mountedUsers.js
import api from '../../apis/mountedUsers'
import * as types from '../types'
const state = {
cities: []
}
const getters = {
cities: state => state.cities
}
const actions = {
getCities({ commit }) {
api.getCities().then(res => {
commit(types.GET_CITIES, res.data)
});
}
}
const mutations = {
[types.GET_CITIES](state, cities) {
state.cities = cities;
}
}
export default {
state,
getters,
actions,
mutations
}
入口文件 main.js
import Vue from 'vue';
import App from './App';
import router from './router';
import store from './store/index';
import ElementUI from 'element-ui';
import 'element-ui/lib/theme-default/index.css'; // 默认主题
import '../static/css/pzq.css';
import "babel-polyfill";
Vue.use(ElementUI);
Vue.config.devtools = true;
new Vue({
router,
store,
render: h => h(App)
}).$mount('#app');
当我在页面中发送this.$store.dispatch('getCities')的时候,报Uncaught (in promise) TypeError: Cannot read property 'cancelToken' of undefined,请问是什么原因呢?
/src/apis/index.js