添加Axios :发请求
import Axios from 'axios'
Vue.prototype.$ajax = Axios;
因为产生跨域,所以配置代理
baseUrl?
// baseUrl
Axios.defaults.baseURL = '/api'
vue.config.js
module.exports = {
configureWebpack: {
devServer:{
proxy:{
'/api':{
target:'http://1.116.64.64:5004/',
changeOrigin:true
}}}}}
按钮的点击事件,添加登录函数
submitForm(formName) {
this.$refs.ruleForm.validate((valid) => {
if (valid) {
this.doLogin(this.ruleForm)
} else {
console.log('error submit!!');
return false;
} });},
登录方法
//登录方法
async doLogin({username,pass}) {
try {
var res = await this.$ajax.post('/user/login', {
account: username,
password: pass
});
console.log(res);
} catch (e) {
console.log(e, 'err')} },
产生错误是因为el-form没有加:model=“ruleForm”,:model 是element-ui里面的属性和v-model不一样。
post 报错,404
原因是把代理文件放在src里面了,拿出来就好了
请求发送成功
得到token
使用axios实例发送请求
let instance = Axios.create({
baseURL:'/api'
})
instance.post("/user/login",{
account:username,
password:pass
})
.then(res => {
console.log(res);
})
.catch(w => {
console.log(e)
});
} catch (e) {
console.log(e, 'err')
}
post请求
登录成功后改变用户状态和用户信息
// 改变用户信息
if(res.data.code === 20000) {
this.changeLogin(true)
// 改变用户信息
this.changeUserInfo({
username:username
});
this.$router.push('/')
} else {
console.log(res)
alert('登录失败')
}
跳转成功