先在vue.congif.js配置代理加上 proxy
proxy: {
'/api': {
target: '192.168.199.85/manage', // 后端地址
// target: 'localhost:8080/manage', // 原始地址
changeOrigin: true, // 开启代理,在本地创建一个虚拟服务端
pathRewrite: {
'^/api': '/'
}
}
}
如果报错 Cannot read property ‘split‘ of null,
是因为 target 的链接没加上http://
然后在 .env.development 文件 把VUE_APP_BASE_API 改了
proxy 写的是 /api 所以这里也是/api
# base api
VUE_APP_BASE_API = '/api'
因为用的不是默认请求头,所以手动添加了一个请求头
// utlis/request.js
axios.defaults.headers['Content-Type'] = 'application/x-www-form-urlencoded'
以登录为例,我这边因为后端原因,需要用到qs,调试,所以就把验证关了
// views/login/index.vue
handleLogin() {
// this.$refs.loginForm.validate(valid => {
// if (valid) {
this.loading = true
this.$store.dispatch('user/login', qs.stringify(this.loginForm))
// this.$store.dispatch('user/login', this.loginForm)
.then(() => {
this.$router.push({ path: this.redirect || '/', query: this.otherQuery })
this.loading = false
})
.catch(() => {
this.loading = false
})
// } else {
// console.log('error submit!!')
// return false
// }
// })
}
// store/modules/user.js
login({ commit }, userInfo) {
return new Promise((resolve, reject) => {
login(userInfo).then(response => {
const { data } = response
commit('SET_TOKEN', data.token)
setToken(data.token)
resolve()
}).catch(error => {
reject(error)
})
})
},