安装axios
npm install axios
main.js配置
// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from 'vue'
import App from './App'
import router from './router'
import ElementUI from 'element-ui'
import axios from '../node_modules/axios'
import 'element-ui/lib/theme-chalk/index.css'
Vue.use(ElementUI, {size: 'medium'})
Vue.prototype.$axios = axios
/* eslint-disable no-new */
new Vue({
el: '#app',
router,
axios,
components: { App },
template: '<App/>'
})
index.js中配置proxy参数
proxyTable: {
'/api': {
target: 'http://127.0.0.1:8082',//设置你调用的接口域名和端口号 别忘了加http
changeOrigin: true,
pathRewrite: {
'^/api': ''//这里理解成用‘/api’代替target里面的地址,后面组件中我们掉接口时直接用api代替 比如我要调用'http://40.00.100.100:3002/user/add',直接写‘/api/user/add’即可
}
}
},
方法调用
methods: {
login () {
if (this.user.password === '' || this.user.userName === '') {
return alert('账户密码不能为空')
}
this.$axios.post('/api/Student/Login', {
userName: this.user.userName,
password: this.user.password
})
.then(successResponse => {
console.log(successResponse)
if (successResponse.data.code === 200) {
this.$router.replace({path: '/index'})
}
})
.catch(failResponse => {})
}
}